Created
November 4, 2018 03:22
-
-
Save zhangxiaomu01/f99218540330fee5376b784a2baa69ed 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(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