【LeetCode141/142】-环形链表

方法一:

实现思路

遍历链表,同时将遍历的元素添加到集合中,判断集合中是否出现过该元素,如果出现过,则说明链表中有环存在。

实现代码

141代码

/**
 * 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) {
    
    
        set<ListNode*> snode;
        while(head!=nullptr){
    
    
            snode.insert(head);
            head=head->next;
            if(snode.find(head)!=snode.end())
                return true;
        }
        return false;
    }
};

142代码

class Solution {
    
    
public:
    ListNode *detectCycle(ListNode *head) {
    
    
                set<ListNode*> snode;
        while(head!=nullptr){
    
    
            snode.insert(head);
            head=head->next;
            if(snode.find(head)!=snode.end())
                return head;
        }
        return nullptr;
    }
};

提交结果及分析:

在这里插入图片描述
在这里插入图片描述

时间复杂度O(n(logn)),空间复杂度O(n)


方法二

实现思路

在这里插入图片描述有环的时候才会出现快指针扣圈的情况
在这里插入图片描述这一推导,有助于下面求解相交节点

实现代码

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44944046/article/details/113003643