5. Linked List Cycle

Link to the problem

Description

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

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

Example

Input: [1,2,3], tail connects to index 0, output: true
Input: [1, 2, 3], output: false

Idea

Use a slow pointer which advance once each time, a fast pointer which advance once each time.
If the linked list has no cycle, then the fast pointer will reach null.
Otherwise, they never stop, but will meet.

Solution

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next) return false;
        ListNode *slow = head, *fast = head->next;
        while (fast) {
            if (slow == fast) return true;
            slow = slow->next;
            fast = fast->next;
            if (!fast) return false;
            fast = fast->next;
        }
        return false;
    }
};

Performance

16 / 16 test cases passed.
Runtime: 6 ms

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 2017-7-9 星期日 天氣晴 寶貝年齡:7周歲4個(gè)月和1周5個(gè)月 學(xué)經(jīng)周期:3年半 學(xué)經(jīng)人員:琦琦。心寶767...
    廈門琦心媽閱讀 254評(píng)論 0 1
  • 我們從說分手開始,到結(jié)束,只用了短短五分鐘
    柏舒稼閱讀 94評(píng)論 0 0
  • 今天是情人節(jié),萬眾撒狗糧的日子,我卻要寫寫我的朋友們。我這人害怕孤獨(dú),總想和大家湊一起,也總認(rèn)為朋友也應(yīng)該天天黏在...
    米蟲后花園閱讀 236評(píng)論 2 1
  • 兔子舞蹈室了?。?!涂涂抹抹,涂抹記錄我跳舞途他們?cè)谀睦餂]有 第二天開始大理Dell路,?咯notturno到大理聚...
    摩旅人閱讀 319評(píng)論 0 0

友情鏈接更多精彩內(nèi)容