天天看點

連結清單中是否存在環的問題,及環入口在連結清單中位置(Linked List Cycle II)

一、學習要點:

1.快慢指針法,存在連結清單環的話,兩指針肯定會相遇;

2.入口位置由兩快慢指針相遇時,改變慢指針指向表頭,和慢指針等速前進,再次相遇的地點決定;

3.講的比較好的一個部落格:https://blog.csdn.net/willduan1/article/details/50938210

二、代碼:

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x):val(x),next(NULL){}
};
class Solution{
public:
	ListNode* detectcycle(ListNode *head)
	{
	ListNode* fast=head;
	ListNode *slow=head;
	bool iscycle=false;
	while(fast&&fast->next)
	{
		fast=fast->next->next;
		slow=slow->next;
		if(slow==fast)
		{
			slow=head;
			while(slow!=head)
			{
				fast=fast->next;
				slow=slow->next;
			}
			return slow;
		}
	}
	return NULL;
}
};