-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19-Remove-Nth-Node-From-End-of-List.cpp
More file actions
66 lines (51 loc) · 1.61 KB
/
Copy path19-Remove-Nth-Node-From-End-of-List.cpp
File metadata and controls
66 lines (51 loc) · 1.61 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Author : Vicen-te
// Date : 09/10/2022
/*
Given the head of a linked list,
remove the nth node from the end of the list and return its head.
Ex.
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
1.- Store the head in two temporary variables
2.- Change the start of the pointer first to start at n
position and check if the input it's null.
3.- Then the first and second pointer keep going until the first reach the end.
the second starts with n-step delay,
the second one by the end will be on the right position.
4.- Then update linkage of second pointer and remove
the N-th node from the end.
5.- Empty(delete the reference: nullptr) and delete the pointers. (MemoryLeaks)
Time: O(N)
Space: O(1)
*/
/**
* 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* first = head;
ListNode* second = head;
for (int i = 0; i < n; i++)
first = first->next;
if (first == nullptr)
return head->next;
while (first->next != nullptr) {
second = second->next;
first = first->next;
}
second->next = second->next->next;
first = nullptr;
second = nullptr;
delete(first);
delete(second);
return head;
}
};