remove-nth-node-from-end-of-list 1.0.0
Remove Nth Node From End of List
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
8struct ListNode
9{
10 int val;
12 ListNode() : val(0), next(nullptr) {}
13 ListNode(int x) : val(x), next(nullptr) {}
14 ListNode(int x, ListNode *next) : val(x), next(next) {}
15};
16
18{
19public:
21 {
22 // two pointers
23 ListNode* current = head;
24 ListNode* remove_next = head; // (n - 1)th from the end
25
26 // move n steps ahead to maintain wanted gap
27 for (int i = 0; i < n; ++i)
28 {
29 if (current == nullptr)
30 return head; // n is larger than the length of the list
31 current = current->next;
32 }
33
34 // n matching list length - removing head
35 if (current == nullptr)
36 {
37 ListNode* removed = head;
38 head = head->next;
39 delete removed;
40 return head;
41 }
42
43 // move pointer window to the end of the list
44 while (current->next != nullptr)
45 {
46 current = current->next;
47 remove_next = remove_next->next;
48 }
49
50 // remove the nth node from the end
51 ListNode* removed = remove_next->next;
52 remove_next->next = remove_next->next->next;
53 removed->next = nullptr;
54 delete removed;
55
56 return head;
57 }
58};
59
61{
62 ListNode* tmp = ptr->next;
63 if (tmp)
64 delete_list(tmp);
65 delete ptr;
66}
67
68int main()
69{
70 ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
71 head = Solution().removeNthFromEnd(head, 2);
72 delete_list(head);
73 return 0;
74}
ListNode * removeNthFromEnd(ListNode *head, int n)
Definition main.cpp:20
int main()
Definition main.cpp:68
void delete_list(ListNode *ptr)
Definition main.cpp:60
Definition for singly-linked list.
Definition main.cpp:9
int val
Definition main.cpp:10
ListNode(int x)
Definition main.cpp:13
ListNode()
Definition main.cpp:12
ListNode * next
Definition main.cpp:11
ListNode(int x, ListNode *next)
Definition main.cpp:14