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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 2017-7-9 星期日 天气晴 宝贝年龄:7周岁4个月和1周5个月 学经周期:3年半 学经人员:琦琦。心宝767...
    厦门琦心妈阅读 1,670评论 0 1
  • 我们从说分手开始,到结束,只用了短短五分钟
    柏舒稼阅读 876评论 0 0
  • 今天是情人节,万众撒狗粮的日子,我却要写写我的朋友们。我这人害怕孤独,总想和大家凑一起,也总认为朋友也应该天天黏在...
    米虫后花园阅读 1,454评论 2 1
  • 兔子舞蹈室了!!!涂涂抹抹,涂抹记录我跳舞途他们在哪里没有 第二天开始大理Dell路,?咯notturno到大理聚...
    摩旅人阅读 2,271评论 0 0

友情链接更多精彩内容