-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove_Nth_Node_From_End_Of_List.cpp
More file actions
41 lines (34 loc) · 1.01 KB
/
Remove_Nth_Node_From_End_Of_List.cpp
File metadata and controls
41 lines (34 loc) · 1.01 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
#include <vector>
//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) {
std::vector<ListNode*> nodes;
ListNode* p = head;
// Put all node pointers into a vector
while (p != nullptr) {
nodes.push_back(p);
p = p->next;
}
// Find index of node to remove
int index = nodes.size()-n;
// Edge case where node to remove is the first one
if (index == 0) {
ListNode* tempHead = head->next;
delete head;
return tempHead;
}
// Get node before the one to remove
ListNode* nodeBefore = nodes[index-1];
nodeBefore->next = nodeBefore->next->next;
delete nodes[index];
return head;
}
};