Skip to content

Instantly share code, notes, and snippets.

@RuiJCS
Created June 4, 2023 10:48
Show Gist options
  • Save RuiJCS/b347681a6ef68420cc065cf71bebef2e to your computer and use it in GitHub Desktop.
Save RuiJCS/b347681a6ef68420cc065cf71bebef2e to your computer and use it in GitHub Desktop.
/**
* 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