Description
Given a linked list, remove the nth node from the end of list and return its head.
Example
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note
Given n will always be valid.
Try to do this in one pass.
##Analyse
一道很有趣的题,题意很简单,就是删除链表倒数第n个的数,做法可以是,先跑一遍链表数出链表长度,然后再算出顺数第几个位置再删去即可,但这种方法需要遍历两次链表,但这道题有趣的是,题目叫我们可以尝试在一次遍历解决问题。其实也很简单,可以一头一尾两个指针同时遍历链表,其中两个指针的间距为n+1,这就能保证当你尾巴那个指针到达链表尾部的时候,头那个指针刚好指的是目标的前一个位置,然后再做一个删除操作即可。
Code
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* ans = new ListNode(-1);
ans->next = head;
ListNode* first = ans;
ListNode* second = ans;
for (int i = 0; i < n + 1; i++) {
first = first->next;
}
while (first != NULL) {
first = first->next;
second = second->next;
}
ListNode* temp = second->next;
delete(temp);
second->next = second->next->next;
return ans->next;
}
};