Skip to content

Commit 9498bba

Browse files
committed
Remove Nth Node From End of List solution
1 parent 99aadbb commit 9498bba

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
ListNode* removeNthFromEnd(ListNode* head, int n) {
4+
ListNode* prev = NULL;
5+
ListNode* curr = head;
6+
ListNode* next = head;
7+
8+
for(int i = 0; next && i < n; i++)
9+
next = next->next;
10+
11+
while(next){
12+
if(prev == nullptr)
13+
prev = head;
14+
else
15+
prev = prev->next;
16+
curr = curr->next;
17+
next = next->next;
18+
}
19+
20+
if(prev == nullptr)
21+
head = curr->next;
22+
else
23+
prev->next = curr->next;
24+
25+
delete(curr);
26+
27+
return head;
28+
}
29+
};

0 commit comments

Comments
 (0)