Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Created March 4, 2019 00:36
Show Gist options
  • Save qiaoxu123/502784605e899994158a8bd85fcd399d to your computer and use it in GitHub Desktop.
Save qiaoxu123/502784605e899994158a8bd85fcd399d to your computer and use it in GitHub Desktop.
> 链表遍历题目。主要考虑使用双指针进行倒计时,保证两个指针的间隔正好是n即可。
//Runtime: 8 ms, faster than 100.00%
//Memory Usage: 9.7 MB, less than 54.37%
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* start = new ListNode(0);
start->next = head;
ListNode* fast = start;
ListNode* slow = start;
for(int i = 1;i <= n;++i)
fast = fast->next;
while(fast->next != NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return start->next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment