双指针找到倒数第N + 1个节点,然后通过这个这节点删除倒数第N个节点。注意head有可能会被删除,我们需要用一个helper节点来帮我们keep track of新的head。O(N)时间,常数空间。代码如下:
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) { | |
ListNode* helper = new ListNode(-1); | |
helper->next = head; | |
auto fast = head, slow = helper; | |
while(n--)fast = fast->next; | |
while(fast) | |
{ | |
fast = fast->next; | |
slow = slow->next; | |
} | |
auto tmp = slow->next; | |
slow->next = tmp->next; | |
tmp->next = nullptr; | |
return helper->next; | |
} | |
}; |
No comments:
Post a Comment