鍊錶 面試題 02 08 環路檢測 快慢指標

2021-10-20 17:34:32 字數 794 閱讀 4767

分析:如果鍊錶中有環,快慢指標肯定能相遇,這個非常容易證明,而且相遇肯定是在環中.

快指標走的倍數是慢指標兩倍,這樣可以非常容易得出迴圈的開始結點

/**

* definition for singly-linked list.

* struct listnode ;

*//**

* definition for singly-linked list.

* struct listnode ;

*/struct listnode *

detectcycle

(struct listnode *head)

//申請快慢指標,快指標是慢指標走的倍數是兩倍

struct listnode *slow=head;

struct listnode *fast=head;

while

(fast!=

null

&&fast->next!=

null

)return slow;}}

return

null

;}

/**

* definition for singly-linked list.

* class listnode

* }*/public

class

solution

return fast;}}

return null;

}}

還是直接套套路就行.

面試題 02 08 環路檢測

面試題 02.08.環路檢測 給定乙個鍊錶,如果它是有環鏈表,實現乙個演算法返回環路的開頭節點。有環鏈表的定義 在鍊錶中某個節點的next元素指向在它前面出現過的節點,則表明該鍊錶存在環路。示例1 輸入 head 3,2,0,4 pos 1 輸出 tail connects to node inde...

面試題 02 08 環路檢測

給定乙個鍊錶,如果它是有環鏈表,實現乙個演算法返回環路的開頭節點。如果鍊錶中有某個節點,可以通過連續跟蹤 next 指標再次到達,則鍊錶中存在環。為了表示給定鍊錶中的環,我們使用整數 pos 來表示鍊錶尾連線到鍊錶中的位置 索引從 0 開始 如果 pos 是 1,則在該鍊錶中沒有環。注意 pos 不...

LeetCode 鍊錶 面試題 反轉鍊錶

題目 於 leetcode 上第 206號 reverse linked list 問題 反轉乙個單鏈表。題目難度為 easy。題目描述 reverse a singly linked list.反轉乙個單鏈表 input 1 2 3 4 5 null output 5 4 3 2 1 null 複...