題目:
Given a linked list, determine if it has a cycle in it.
思路與步驟:
採用“快慢指針”查檢查鏈表是否含有環。讓一個指針一次走一步,另一個一次走兩步,如果鏈表中含有環,快指針會再次和慢指針相遇。
編程實現:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode fast = head;
ListNode slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow) return true;
}
return false;
}
}
注意循環條件!否則會有異常
while(fast.next!=null && fast.next.next!=null)