天天刷leetcode(2) ---- 141.Linked List Cycle

问题描述

Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.

给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos不作为参数进行传递,仅仅是为了标识链表的实际情况。

如果链表中存在环,则返回 true 。 否则,返回 false 。

思路

1.建立空hash表,遍历链表,逐个将链表元素加入到hash表中,如果当前元素在hash表中已经存在,则认为存在环。代码如下

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> visited;
        while(head){
            if(visited.count(head)) return true;
            visited.insert(head);
            head=head->next;
        }
        return false;
    }
};

2.使用快慢指针,快指针一次前进两步,慢指针一次前进一步,当两个指针的位置有重合时,认为存在环。代码如下

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

这里要注意,while(·)循环开始后,要首先判断fast的下一步是否是空,才能进行前进两步的操作。
快慢指针的算法原理如下图所示。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值