2.5

Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE

input: A -> B -> C -> D -> E -> C [the same C as earlier]

output: C

分析:這也是一道鏈表的經常討論的題目。有些題目是判斷鏈表中是否有環?方法是使用一個快指針,一個慢指針,兩者必定相遇;有些題目是判斷鏈表是否相交,這個的解法就比較多。

我開始確實也沒有想明白,研究了一下答案。如果A表示慢指針、B表示快指針,當A到達環入口點的時候,假設B領先A k個位置,則他們相遇的地方一定距離入口點k個位置。因爲如果A、B同在起始點,則相遇點也在起始點。B領先k個位置,則相遇點距離起點點反方向k個位置。


代碼:

Node* find_loop_start(Node* head){
	if(head==NULL) return;
	Node* fast=head,*slow=head;
	while(1){
		slow=slow->next;
		fast=fast->next;
		if(fast!=NULL){
			fast=fast->next;
			if(fast==slow)
				break;
		}
		else
			break;
	}
	if(fast==NULL)
		return NULL;
	slow=head;
	while(1){
		if(slow==fast)
			return fast;
		slow=slow->next;
		fast=fast->next;
	}
}


發佈了286 篇原創文章 · 獲贊 8 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章