Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解決鏈表問題的經典做法:使用倆指針fast和slow,判斷最後fast是爲null還是fast==slow即可。
public class LinkedListCycle {
/*
* 思路:使用 兩個指針slow和fast 看最後有沒有相遇
*/
public boolean hasCycle2(ListNode head) {
if(head==null) return false;
ListNode slow = head;
ListNode fast = head;
boolean flag = false;
while(fast!=null && fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
flag = true;
break;
}
}
return flag;
}
public boolean hasCycle(ListNode head) {
if(head==null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow!=fast) {
if(fast==null || fast.next==null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}