-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNodeFromEndofList.cpp
More file actions
66 lines (57 loc) · 998 Bytes
/
RemoveNthNodeFromEndofList.cpp
File metadata and controls
66 lines (57 loc) · 998 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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 *p,*q,*last;
p=head;
if(p->next==NULL){
return NULL;
}
q=p;
while(q->next!=NULL){
q=p;
for(int i=0;i<n;i++){
q=q->next;
if(q==NULL&&p==head){
return head->next;
}
}
cout<<"p: "<<p->val<<"-------";
cout<<"q: "<<q->val<<endl;
last=p;
p=p->next;
}
last->next=last->next->next;
return head;
}
};
int main(){
int n;
cin>>n;
int num;
cin>>num;
ListNode *p=new ListNode(num);
ListNode *head=p;
for(int i=1;i<n;i++){
cin>>num;
ListNode *q=new ListNode(num);
p->next=q;
p=q;
}
p->next=NULL;
int target;
cin>>target;
Solution *solution=new Solution();
head=solution->removeNthFromEnd(head,target);
while(head!=NULL){
cout<<head->val<<endl;
head=head->next;
}
return 0;
}