Skip to content

Commit 80de0d8

Browse files
committed
Create Remove Nth Node From End of List.cpp
1 parent e031f5c commit 80de0d8

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Remove Nth Node From End of List.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *removeNthFromEnd(ListNode *head, int n) {
12+
// Start typing your C/C++ solution below
13+
// DO NOT write int main() function
14+
ListNode *p1=head,*p2=head,*pre;
15+
int c=n;
16+
while (c--)p2=p2->next;
17+
if (!p2)
18+
{
19+
ListNode *tmp=head;
20+
head=head->next;
21+
delete tmp;
22+
return head;
23+
}
24+
while (p2)
25+
{
26+
pre=p1;
27+
p1=p1->next;
28+
p2=p2->next;
29+
}
30+
ListNode *tmp=p1;
31+
pre->next=p1->next;
32+
delete tmp;
33+
return head;
34+
}
35+
};

0 commit comments

Comments
 (0)