Given a linked list, remove the nth node from the end of list and return its head.
For 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.
解:链表本来只能从表头开始遍历,一开始无法知道链表的长度,如何能够知道从链表尾部的第几个元素是难点,其实只要先从头部遍历n个,然后同时从头部和中间第n个开始遍历到尾部就能找到从链表尾部的第几个元素。
/**
* 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* tmp = head;
ListNode** tmp2 = &head;
for(int i = 1; i < n; ++i){
tmp = tmp->next;
}
while(tmp->next != NULL){
tmp2 = &((*tmp2)->next);
tmp = tmp->next;
}
*tmp2 = (*tmp2)->next;
return head;
}
};