Linked List Cycle,linkedlistcycle

來源:互聯網
上載者:User

Linked List Cycle,linkedlistcycle

本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/42833739



Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


思路:

(1)題意為判斷一個鏈表是否帶環。這道題在校招筆試和面試中出現的次數還是比較多的。

(2)要判斷是否帶環,只需設定兩個指標,從鏈表的起始點開始,分別往後遍曆鏈表中的節點,如果在遍曆的過程中兩指標相遇,說明鏈錶帶有環。但是為了讓它們在鏈錶帶環的情況下能夠相遇,需要對兩指標設定不同的步調,一個指標每次前進一步,另一個指標一次前進兩步,這樣如果前一個指標遍曆到最後一個節點為空白,則說明鏈表不帶環;否則在遍曆的過程中如果第一個指標和第二個指標相遇,則說明鏈錶帶環。

(3)希望本文對你有所協助。


演算法代碼實現如下:

/** * @author liqq */public boolean hasCycle(ListNode head) {if (head == null || head.next == null)return false;ListNode curr = head;ListNode sec = head;while (sec.next != null && sec.next.next != null) {curr = curr.next;sec = sec.next.next;if (curr == sec) {return true;}}return false;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.