Created
June 4, 2023 10:48
-
-
Save RuiJCS/b347681a6ef68420cc065cf71bebef2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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: | |
pair<ListNode *, int> runThroughList(ListNode *current, int n) | |
{ | |
if (current->next == nullptr) | |
{ | |
if (n == 1) | |
{ | |
delete current; | |
return pair{nullptr, 1}; | |
} | |
return pair{current, 1}; | |
} | |
else | |
{ | |
pair<ListNode *, int> next = runThroughList(current->next, n); | |
int index = ++next.second; | |
cout << current->val << " " << index << " "; | |
if (index == n) | |
{ | |
delete current; | |
} | |
else | |
{ | |
current->next = next.first; | |
next.first = current; | |
} | |
return next; | |
} | |
} | |
ListNode *removeNthFromEnd(ListNode *head, int n) | |
{ | |
return runThroughList(head, n).first; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment