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.
这一题思路是十分典型的,设置两个指针first,end同时指向head,然后向后移动end指针n-1次,在开始同时移动first和end指针,当end指针指向链表末尾时,first指针则指向Nth node from the end of List
代码如下:
/**
* 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* first = head,*end=head,*tmp=head;
for(int i=0;i<n-1;i++)
{
end = end->next;
}
while(end->next != NULL)
{
tmp = first;
first = first->next;
end = end->next;
}
if(tmp == first)
head=tmp->next;
else
tmp->next = first->next;
return head;
}
};