Remove Nth Node From End of List

描述

Given a linked list, remove the n-th node from the end of list and return its head.

For example, Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

  • Given n will always be valid.
  • Try to do this in one pass.

    分析

设两个指针p,q,让q先走n步,然后pq一起走,直到q走到尾节点,删除p->next即可。

代码

  1. // Remove Nth Node From End of List
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public ListNode removeNthFromEnd(ListNode head, int n) {
  5. ListNode dummy = new ListNode(-1);
  6. dummy.next = head;
  7. ListNode p = dummy, q = dummy;
  8. for (int i = 0; i < n; i++) // q先走n步
  9. q = q.next;
  10. while(q.next != null) { // 一起走
  11. p = p.next;
  12. q = q.next;
  13. }
  14. p.next = p.next.next;
  15. return dummy.next;
  16. }
  17. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/remove-nth-node-from-end-of-list.html