給定一個鏈表面褐,判斷鏈表中是否有環(huán): https://leetcode-cn.com/problems/linked-list-cycle/submissions/
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1程腹,則在該鏈表中沒有環(huán)痛垛。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環(huán),其尾部連接到第二個節(jié)點卷哩。
circularlinkedlist.png
來源:力扣(LeetCode)
思路:使用快慢指針
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false; 少于兩個節(jié)點,直接返回false
ListNode fast = head.next;快指針
ListNode slow = head; 慢指針
while(fast != slow ){ 循環(huán)條件 快慢指針不相遇
if(fast == null || fast.next == null) return false; 快指針出現(xiàn)null,證明到了節(jié)點末尾,則沒有環(huán)
fast = fast.next.next; 快指針走兩步
slow = slow.next; 慢指針走一步
}
return true; 快慢指針相遇,有環(huán)
}
}