Skip to content

Commit e0edb66

Browse files
committed
Time: 8 ms (44.48%), Space: 10.7 MB (74.80%) - LeetHub
1 parent 0c90b7b commit e0edb66

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
typedef struct ListNode node;
12+
class Solution {
13+
public:
14+
ListNode* removeNthFromEnd(ListNode* head, int n) {
15+
node* dummy = new node(0);
16+
dummy->next = head;
17+
18+
node* right = head;
19+
node* left = head;
20+
node* prev = dummy;
21+
22+
// [-------------------------------]
23+
// n L-n
24+
// [-------------|-----------------]
25+
// L-n | n
26+
27+
int cnt = n;
28+
while(right != NULL and cnt--) {
29+
// right traverses n steps
30+
right = right->next;
31+
}
32+
33+
while(right != NULL) {
34+
// right traverses (L-n) steps
35+
right = right->next;
36+
prev = left;
37+
left = left->next;
38+
}
39+
40+
prev->next = left->next;
41+
42+
return dummy->next;
43+
}
44+
};

0 commit comments

Comments
 (0)