0%

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* target = head;
int size = 0;
ListNode* iterator = head;
while (iterator != nullptr)
{
++size;
iterator = iterator->next;
}

for (int i = 0; i < size - n - 1; ++i)
{
target = target->next;
}
if (size - n - 1 == -1)
{
head = head->next;
}
if (target->next != nullptr)
target->next = target->next->next;
return head;
}
};
discussion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *start = new ListNode();
ListNode *fast = start, *slow = start;
start->next = head;
for (int i = 0; i < n + 1; ++i)
{
fast = fast->next;
}
while(fast != nullptr)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return start->next;
}
};
review
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode ret;
ret.next = head;
ListNode* runner = &ret, *walker = &ret;
while(n--)
runner = runner->next;
while(runner->next)
{
walker = walker->next;
runner = runner->next;
}
walker->next = walker->next->next;
return ret.next;
}
};