LeetCode第 141 题:环形链表(C++)

141. 环形链表 - 力扣(LeetCode)
在这里插入图片描述

快慢指针

慢指针:一次走一步
快指针:一次走两步
如果指向 NULL 则无环,若有环两者必然会相等。
注意边界条件判断。。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        // 1个结点无法构成环
        if(head == NULL || head->next == NULL)
            return false;
        auto slow_p = head;
        auto fast_p = head->next;
        while(slow_p != fast_p){
            if(fast_p == NULL || fast_p->next == NULL){
                return false;
            }else{
                slow_p = slow_p->next;
                fast_p = fast_p->next->next;
            }
        }
        return true;
    }
};

标记法

把遍历过的节点值都置为一个不太可能出现的值。。。

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

遍历链表,若有环,则必定有元素被重复遍历

利用关联容器unordered_set:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode *> c_set;
        while(head != NULL){
            if(c_set.count(head))
                return true;
            c_set.insert(head);
            head = head->next;
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值