Skip to content

Commit deed26d

Browse files
authored
Merge pull request #95 from Ibraam-Nashaat/main
Create 19-Remove-Nth-Node-From-End-of-List.cpp
2 parents bb7ede8 + e38ad19 commit deed26d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* removeNthFromEnd(ListNode* head, int n) {
14+
if(!head) return head;
15+
ListNode* f,*s,*prev;
16+
f=head;
17+
s=head;
18+
prev=nullptr;
19+
for(int i=0;i<n;i++)
20+
f=f->next;
21+
while(f)
22+
{
23+
prev=s;
24+
s=s->next;
25+
f=f->next;
26+
}
27+
if(prev)
28+
prev->next=s->next;
29+
else
30+
head=head->next;
31+
delete s;
32+
return head;
33+
}
34+
};

0 commit comments

Comments
 (0)