This file contains hidden or 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: | |
ListNode* removeNthFromEnd(ListNode* head, int n) { | |
auto fast = head; | |
auto slow = head; | |
// fast: move n step | |
while(n){ | |
fast = fast->next; | |
n--; | |
} | |
// if reaches the tail, remove head | |
if(!fast){ | |
head = head->next; | |
return head; | |
} | |
// move fast to tail | |
while(fast->next){ | |
fast = fast->next; | |
slow = slow->next; | |
} | |
// remove | |
slow->next = slow->next->next; | |
return head; | |
} | |
}; |
No comments:
Post a Comment