Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//Handle situation that list is null or only contain one element
if(!head || !(head->next))
return nullptr;
ListNode *fast = head, *slow =head;
int count = 0;
while(fast->next != nullptr)
{
fast = fast->next;
count ++;
if(count> n)
{
slow = slow->next;
}
}
//Handles situation that we need to delete first node. e.g. [1,2] 2
if(count + 1 == n)
{
head = head-> next;
delete slow;
return head;
}
ListNode *temp = slow->next;
if(temp == nullptr)
return nullptr;
slow->next = temp->next;
delete temp;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment