-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path019_Remove_Nth_Node_From_End_of_List.cpp
63 lines (63 loc) · 1.4 KB
/
019_Remove_Nth_Node_From_End_of_List.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode *pre, *cur, *sentienl;
cur = head;
sentienl = cur;
int count = 0;
while( count < n)
{
count++;
sentienl = sentienl->next;
}
if( sentienl == NULL)
{
return head->next;
}
else
{
pre = head;
cur = head->next;
sentienl = sentienl->next;
while(sentienl != NULL )
{
pre = pre->next;
cur = cur->next;
sentienl = sentienl->next;
}
pre->next = cur->next;
return head;
}
}
};
int main(int argc, char const *argv[])
{
ListNode a(1), b(2), c(3), d(4), e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution sol;
//ListNode* res = sol.removeNthFromEnd(&a, 3);
ListNode* res = sol.removeNthFromEnd(&a, 3);
while( res != NULL)
{
cout<<res->val<<"\t";
res =res->next;
}
return 0;
}