题目:
Given a linked list, remove the n th 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.
解题思路:
定义两个指针,让快、慢指针同时指向头结点;然后让快指针先走n步,在让两个指针同时走,直到快指针走到结尾。这时,慢指针指向的结点就是要删除的结点。
代码实现:
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == NULL)
return NULL;
if(n < 0)
return head;
//计算节点个数
int count = 0;
ListNode* cur = head;
while(cur)
{
count++;
cur = cur->next;
}
if(n > count)
return head;
ListNode* fast = head;
ListNode* slow = head;
while(n--)
{
fast = fast->next;
}
ListNode* pre = NULL;
while(slow && fast)
{
pre = slow;
slow = slow->next;
fast = fast->next;
}
if(slow == head)
{
head = head->next;
}
else
pre->next = slow->next;
delete slow;
return head;
}
};