-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet19.cpp
More file actions
57 lines (53 loc) · 1.18 KB
/
Copy pathleet19.cpp
File metadata and controls
57 lines (53 loc) · 1.18 KB
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
#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 *th = new ListNode(-1) ;
th->next = head ;
ListNode *x = head ;
int i = 1 ;
while(x!=NULL && i<n){
x = x->next ;
i++ ;
}
ListNode *y = th ;
while(x->next!=NULL){
x = x->next ;
y = y->next ;
}
if(y == th){
y->next = y->next->next ;
return y->next ;
}else{
y->next = y->next->next ;
return head ;
}
}
};
int main(){
int n = 5;
ListNode *head = new ListNode(5) ;
for(int i=1 ;i<n ;i++){
ListNode *t = new ListNode(i) ;
t->next = head ;
head = t ;
}
ListNode *st = head ;
while(st != NULL){
cout << st->val << " " ;
st = st->next ;
}
cout << endl ;
Solution sl ;
ListNode *res = sl.removeNthFromEnd(head, 5) ;
while(res != NULL){
cout << res->val << " " ;
res = res->next ;
}
}