標籤:style blog http io color sp on div 2014
| 標題: |
Linked List Cycle |
| 通過率: |
36% |
| 難度 |
中等 |
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
拿到題後我以為很簡單,題目中給出不用額外的空間我不知道什麼意思,我單純的認為判斷是否有環,如果是我認為單純的一個環那麼只用用一個節點去記錄頭結點,然後開始迴圈遍曆,直到再次回到頭部。如果能回到便是一個迴圈鏈。提交代碼後發現提示為:
| Last executed input: |
{3,2,0,-4}, tail connects to node index 1 |
突然就蒙圈了!怎麼會出現這種迴圈鏈表呢,我都驚呆了。然後我就只能開始查資料了。我用個圖來展示這個問題的
對於這種鏈表我都醉了。到底要如何去判斷有沒有環環,我只能又去尋找了。
經過尋找我發現網上最為流行且效率最高的便是兩個指標開始遍曆且速度不一樣,具體怎麼處理的我下面進行詳細解釋:
1、設定兩個指標:A、B,且開始時都指向頭部
2、A的遍曆方式為:A=A.next,即一步一步走。B的遍曆方式為:B=B.next.next,即一次走兩步。
有了以上兩個方式,我們可以想如果有環那麼B一定是可以追上A的。如果沒有環那麼B將最先走到最後。
有了上面的解釋我相信已經很明確了。下面直接上代碼來進行具體闡述:
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head==null) return false; 4 if(head.next==null) return false; 5 if(head.next.next==null) return false; 6 7 ListNode slow=head; 8 ListNode fast=head; 9 10 while(fast!=null && fast.next!=null){11 slow=slow.next;12 fast=fast.next.next;13 if(fast==slow){14 return true;15 }16 }17 return false;18 19 }20 }
leetcode------Linked List Cycle(3)