前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 141 Linked List Cycle

Leetcode 141 Linked List Cycle

作者头像
triplebee
发布2018-01-12 14:53:09
5000
发布2018-01-12 14:53:09
举报

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

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

判断链表中是否存在环,

通常的想法是用一个map或者set记录出现过的点,然而这题不让使用额外的空间。

所以可以使用快慢指针,只要存在环,那么快指针迟早会追尾慢指针

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode* p = head;
        ListNode* q = head;
        while(p && q->next)
        {
            if(!q->next->next) break;
            q = q->next->next;
            p = p->next;
            if(p == q) return true;
        }
        return false;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-11-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档