Leetcode-19 Remove Nth Node From End of List

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.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Example 1

1
2
3
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.

解题思路

双指针 pq。两指针相距 n,移动两个指针直至 q 到达末尾。此时 p 指向待删除节点的前面。当删除第一个节点时,需要增加哑节点。

复杂度分析

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p = new ListNode(0), *q = p;
p->next = head;
head=p;
while (q->next) {
if (n-- <= 0)
p=p->next;
q=q->next;
}
p->next = p->next->next;
return head->next;
}
};