-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution019.cpp
More file actions
50 lines (44 loc) · 900 Bytes
/
Copy pathsolution019.cpp
File metadata and controls
50 lines (44 loc) · 900 Bytes
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Remove Nth Node From End of List
* Double pointer.
*
* cpselvis(cpselvis@gmail.com)
* August 18th, 2016
*/
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast = head, *slow = head;
while (n --)
{
fast = fast -> next;
}
while (fast == NULL)
{
return head -> next;
}
while (fast -> next != NULL)
{
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
return head;
}
};
int main(int argc, char **argv)
{
Solution s;
ListNode *p = new ListNode(1);
// p -> next = new ListNode(2);
// p -> next -> next = new ListNode(3);
ListNode *ret = s.removeNthFromEnd(p, 1);
cout << ret -> val << endl;
}