首页 > 其他 > 详细

判断链表成环【快慢指针】

时间:2021-01-24 21:48:28      阅读:29      评论:0      收藏:0      [点我收藏+]

题目描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
你能给出空间复杂度的解法么?

说明:本题目包含复杂数据结构ListNode,点此查看相关信



#define Node ListNode
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL || head->next==NULL) return false;
        Node*first = head,*last = first;
        while(first && first->next ){
            first=first->next->next,last=last->next;
            if(first==last) break;
        }
        if(first && first->next && first==last) return true;
        return false;
    }
};

判断链表成环【快慢指针】

原文:https://www.cnblogs.com/lyr-2000/p/14322441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!