19 删除链表的倒数第N个节点

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode removeNthFromEnd(ListNode head, int n) {
  13. ListNode pHead = new ListNode(-1);
  14. pHead.next = head;
  15. ListNode p = pHead;
  16. for (int i = 1; i <= n + 1; ++i)
  17. p = p.next;
  18. ListNode q = pHead;
  19. while (p != null) {
  20. p = p.next;
  21. q = q.next;
  22. }
  23. p = q.next;
  24. q.next = p.next;
  25. return pHead.next;
  26. }
  27. }