Skip to content

Commit f40b55f

Browse files
committed
add remove_nth_node_from_end_of_list.cpp
1 parent b5bf8fe commit f40b55f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

remove_nth_node_from_end_of_list.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
ListNode* front = head;
13+
ListNode* behind = head;
14+
ListNode* behind2 = NULL;
15+
for (int i = 0; i < n; ++i)
16+
front = front->next;
17+
18+
while (front != NULL)
19+
{
20+
front = front->next;
21+
behind2 = behind;
22+
behind = behind->next;
23+
}
24+
25+
if (behind2 == NULL) // head will be deleted
26+
return behind->next;
27+
28+
behind2->next = behind->next;
29+
return head;
30+
}
31+
};

0 commit comments

Comments
 (0)