leetcode------Linked List Cycle(3)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.