快慢指针法解决链表倒数第K个结点的问题。
快慢指针在链表中经常用到,是一种非常常见的算法。其中,快慢指针可以用来求解链表的倒数第K个结点。
方法如下:(假设当前链表的长度m,要求倒数第k个链表结点)
①首先建立两个指针引用,分别为slow,fast。一开始都为head头结点
②fast指针移动k-1次,此时fast指针位于链表的第k个结点位置处。
③fast与slow指针同时向后移动,当fast指针指向链表末尾时,slow指针位于链表倒数第k个位置处。
算法原理:
fast指针位于第k个结点后,再次移动m-k次到达链表的最后一个结点。此时,slow与fast移动速度相同,则slow也移动了m-k次,那么slow到了链表的第m-k+1个结点处,显而易见m-k+1即为倒数第k个结点。
下面给出算法实现例子:
删除倒数第K个结点(LeeTCode19)
Given a linked list, remove the n-th 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.
Follow up:
Could you do this in one pass?
题目很简单,就是删除链表的倒数第K个结点。转换一下,就是先求出倒数第K+1个结点temp,然后再删除就可以了。
这里要注意:需要先判断是否删除的是第一个结点,如果删除第一个直接返回head->next就可以啦。
代码如下:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast=head;
ListNode* slow=head;
int len=0;
for(slow;slow!=NULL;slow=slow->next)
len++;
if(n==len)
return head->next;
slow=head;
n=n+1;
for(int i=0;i<n-1;i++)
fast=fast->next;
while(fast->next!=NULL)
{
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return head;
}
};