remove-nth-node-from-end-of-list 1.0.0
Remove Nth Node From End of List
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

ListNoderemoveNthFromEnd (ListNode *head, int n)
 

Detailed Description

Definition at line 17 of file main.cpp.

Member Function Documentation

◆ removeNthFromEnd()

ListNode * Solution::removeNthFromEnd ( ListNode head,
int  n 
)
inline

Definition at line 20 of file main.cpp.

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 }
Definition for singly-linked list.
Definition main.cpp:9
ListNode * next
Definition main.cpp:11

References ListNode::next.

Referenced by main().


The documentation for this class was generated from the following file: