leetcode solution: Remove Nth Node From End of List (19)

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

For example,

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.

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

解法1: Two pointers, One Pass, O(N) Time

头node不确定,上dummy node大法。然后用双指针向前移动,找到Nth node的前一个node,删除后返回dummy->next
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* left = dummy;
head = dummy;
for (int i = 0; i < n; ++i) {
head = head->next;
}
while (head->next) {
left = left->next;
head = head->next;
}
ListNode* temp = left->next;
left->next = left->next->next;
ListNode* res = dummy->next;
delete temp;
delete dummy;
return res;
}
};

Java

1