Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
經典問題,判斷一個單向連結清單是否有環,快慢指針,有相遇即有環。
/**
* 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)
return false;
ListNode fast = head, slow = head;
int cnt = 0;
while (true) {
if (fast == null)
return false;
if (cnt > 0 && fast == slow)
return true;
slow = slow.next;
fast = fast.next;
if (slow == null || fast == null)
return false;
fast = fast.next;
cnt ++;
}
}
}
作者:Pickle
出處:http://www.cnblogs.com/wxisme/
聲明:對于轉載分享我是沒有意見的,出于對部落格園社群和作者的尊重一定要保留原文位址哈。
緻讀者:堅持寫部落格不容易,寫高品質部落格更難,我也在不斷的學習和進步,希望和所有同路人一道用技術來改變生活。覺得有點用就點個贊哈。