题目描述
给你一个链表的头节点 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) {
<

本文介绍了两种方法检查链表中是否存在环:一是使用哈希表记录已访问节点,二是利用快慢指针策略。第一种方法的时间复杂度为O(N),空间复杂度也为O(N);第二种方法的时间复杂度为O(N)(无环)或O(1)(有环),空间复杂度为O(1)。
最低0.47元/天 解锁文章
1180

被折叠的 条评论
为什么被折叠?



