【力扣 - 环形链表】

题目描述

给你一个链表的头节点 head ,判断链表中是否有环。

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

如果链表中存在环 ,则返回 true 。 否则,返回 false 。
在这里插入图片描述
在这里插入图片描述

题解一: 哈希表

思路及算法

最容易想到的方法是遍历所有节点,每次遍历到一个节点时,判断该节点此前是否被访问过。

具体地,我们可以使用哈希表来存储所有已经访问过的节点。每次我们到达一个节点,如果该节点已经存在于哈希表中,则说明该链表是环形链表,否则就将该节点加入哈希表中。重复这一过程,直到我们遍历完整个链表即可。

代码

#include <stdbool.h>
#include <stdlib.h>
#include "uthash.h" // Include the uthash library for hash table operations

// Define a structure for the hash table entry
struct hashTable {
    struct ListNode* key; // ListNode pointer as the key
    UT_hash_handle hh; // UTHASH handle for hashtable
};

struct hashTable* hashtable; // Declare a pointer to the hash table

// Function to find a ListNode in the hash table
struct hashTable* find(struct ListNode* ikey) {
    struct hashTable* tmp; // Temporary pointer
    HASH_FIND_PTR(hashtable, &ikey, tmp); // Find the entry with the given key
    return tmp; // Return the pointer to the entry (NULL if not found)
}

// Function to insert a ListNode into the hash table
void insert(struct ListNode* ikey) {
    struct hashTable* tmp = malloc(sizeof(struct hashTable)); // Allocate memory for a new hash table entry
    tmp->key = ikey; // Set the key of the entry
    HASH_ADD_PTR(hashtable, key, tmp); // Add the entry to the hash table
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
// Function to check if a linked list has a cycle
bool hasCycle(struct ListNode* head) {
    hashtable = NULL; // Initialize the hash table to be empty

    while (head != NULL) {
        if (find(head) != NULL) { // If the current node is already in the hash table
            return true; // There is a cycle
        }
        insert(head); // Insert the current node into the hash table
        head = head->next; // Move to the next node in the linked list
    }

    return false; // No cycle found
}
/*
In the code above, the  `HASH_FIND_PTR`  macro is used to find an entry in the hash table based on a pointer key. Here is how  `HASH_FIND_PTR`  works:

1. Parameters:
   - The  `HASH_FIND_PTR`  macro takes three parameters:
     - The hash table name (in this case,  `hashtable` )
     - A pointer to the key being searched (in this case,  `&ikey` )
     - A pointer to a variable where the result will be stored (in this case,  `tmp` )

2. Functionality:
   -  `HASH_FIND_PTR`  is a macro provided by the uthash library that performs a lookup in the hash table.
   - It takes the hash table name and the pointer to the key to be found.
   - If an entry with a matching key is found in the hash table, the third parameter ( `tmp`  in this case) will be assigned a pointer to that entry.
   - If no matching entry is found, the third parameter will be set to  `NULL` .

3. Usage in the Code:
   - In the  `find`  function,  `HASH_FIND_PTR`  is used to search for a  `ListNode`  pointer ( `ikey` ) in the hash table ( `hashtable` ).
   - If a matching entry is found, the function returns a pointer to that entry. Otherwise, it returns  `NULL` .

4. Return Value:
   - The result of  `HASH_FIND_PTR`  is stored in the variable  `tmp` , which is then returned by the  `find`  function.

Overall,  `HASH_FIND_PTR`  simplifies the process of searching for a specific entry in a hash table based on a pointer key.
*/

复杂度分析

时间复杂度:O(N),其中 N 是链表中的节点数。最坏情况下我们需要遍历每个节点一次。
空间复杂度:O(N),其中 N 是链表中的节点数。主要为哈希表的开销,最坏情况下我们需要将每个节点插入到哈希表中一次。

题解二:快慢指针

思路及算法

本方法需要读者对「Floyd 判圈算法」(又称龟兔赛跑算法)有所了解。

假想「乌龟」和「兔子」在链表上移动,「兔子」跑得快,「乌龟」跑得慢。当「乌龟」和「兔子」从链表上的同一个节点开始移动时,如果该链表中没有环,那么「兔子」将一直处于「乌龟」的前方;如果该链表中有环,那么「兔子」会先于「乌龟」进入环,并且一直在环内移动。等到「乌龟」进入环时,由于「兔子」的速度快,它一定会在某个时刻与乌龟相遇,即套了「乌龟」若干圈。

我们可以根据上述思路来解决本题。具体地,我们定义两个指针,一快一慢。慢指针每次只移动一步,而快指针每次移动两步。初始时,慢指针在位置 head,而快指针在位置 head.next。这样一来,如果在移动的过程中,快指针反过来追上慢指针,就说明该链表为环形链表。否则快指针将到达链表尾部,该链表不为环形链表。
在这里插入图片描述

细节

为什么我们要规定初始时慢指针在位置 head,快指针在位置 head.next,而不是两个指针都在位置 head(即与「乌龟」和「兔子」中的叙述相同)?

观察下面的代码,我们使用的是 while 循环,循环条件先于循环体。由于循环条件一定是判断快慢指针是否重合,如果我们将两个指针初始都置于 head,那么 while 循环就不会执行。因此,我们可以假想一个在 head 之前的虚拟节点,慢指针从虚拟节点移动一步到达 head,快指针从虚拟节点移动两步到达 head.next,这样我们就可以使用 while 循环了。

当然,我们也可以使用 do-while 循环。此时,我们就可以把快慢指针的初始值都置为 head。

// Function to detect a cycle in a linked list
bool hasCycle(struct ListNode* head) {
    // Check if the linked list is empty or has only one node
    if (head == NULL || head->next == NULL) {
        return false; // No cycle in this case
    }

    // Initialize two pointers - slow and fast,to traverse the linked list at different speeds. 
    struct ListNode* slow = head;
    struct ListNode* fast = head->next;

    // Move the pointers until they meet or fast reaches the end of the list
    while (slow != fast) {
        // If fast reaches the end of the list (or the next node is NULL), no cycle exists
        if (fast == NULL || fast->next == NULL) {
            return false;
        }
        // Move the slow pointer by one step and the fast pointer by two steps
        slow = slow->next;
        fast = fast->next->next;
    }

    return true; // If the loop breaks because slow and fast meet, a cycle exists
}

复杂度分析

时间复杂度:O(N),其中 N 是链表中的节点数。
当链表中不存在环时,快指针将先于慢指针到达链表尾部,链表中每个节点至多被访问两次。

当链表中存在环时,每一轮移动后,快慢指针的距离将减小一。而初始距离为环的长度,因此至多移动 NNN 轮。

空间复杂度: O(1)。我们只使用了两个指针的额外空间。

作者:力扣官方题解
链接:https://leetcode.cn/problems/linked-list-cycle/solutions/440042/huan-xing-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 33
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值