LeetCode 141 Linked List Cycle(set、map、快慢指针)

题目链接:点击这里

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

set判重:

/**
 * 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) {
        unordered_set<ListNode*> st;
        while(head!=NULL)
        {
            if(st.count(head))  return true;
            st.insert(head);
            head = head->next;
        }
        return false;
    }
};

map:

/**
 * 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) {
        unordered_map<ListNode*, int> mp;
        while(head!=NULL)
        { 
            if(mp[head]==2) return true;
            mp[head]++;
            head = head->next;
        }
        return false;
    }
};

快慢指针:

单链表的特点是每个节点只知道下一个节点,所以,只用一个指针无法判断链表中是否含有环。

  • 如果链表中不含环,那么这个指针最终会遇到空指针 null 表示链表到头了,这还好说,可以判断该链表不含环。

  • 但是如果链表中含有环,那么这个指针就会陷入死循环,因为环形数组中没有 null 指针作为尾部节点。

经典解法就是用两个指针,一个跑得快,一个跑得慢。

  • 如果不含有环,跑得快的那个指针最终会遇到 null,说明链表不含环;
  • 如果含有环,快指针最终会超慢指针一圈,和慢指针相遇,说明链表含有环。
/**
 * 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) {
        ListNode *fast = head, *slow = head;
        while(fast!=NULL && fast->next!=NULL)
        {
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow)  return true;
        }
        return false;
    }
};
发布了706 篇原创文章 · 获赞 104 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104099151