Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created November 4, 2018 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/f99218540330fee5376b784a2baa69ed to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/f99218540330fee5376b784a2baa69ed to your computer and use it in GitHub Desktop.
/**
* 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