【力扣 简单 C】141. 环形链表
目录
题目
解法一:哈希
解法二:快慢指针
题目
解法一:哈希
struct node
{struct ListNode* val;struct node* next;
};struct hashSet
{struct node** bucket;int size;
};struct hashSet* hashSetInit(int size)
{struct hashSet* hashSet = malloc(sizeof(*hashSet));hashSet->bucket = calloc(size, sizeof(*hashSet->bucket));hashSet->size = size;return hashSet;
}long long hash(struct hashSet* hashSet, struct ListNode* val)
{return ((long long)val >> 7) % hashSet->size;
}void hashSetInsert(struct hashSet* hashSet, struct ListNode* val)
{long long index = hash(hashSet, val);struct node* newNode = malloc(sizeof(*newNode));newNode->val = val;newNode->next = hashSet->bucket[index];hashSet->bucket[index] = newNode;
}bool hashSetFind(struct hashSet* hashSet, struct ListNode* val)
{long long index = hash(hashSet, val);struct node* curNode = hashSet->bucket[index];while (curNode){if (curNode->val == val)return true;curNode = curNode->next;}return false;
}void hashSetFree(struct hashSet* hashSet)
{for (int i = 0; i < hashSet->size; i++){struct node* freeNode = hashSet->bucket[i];while (freeNode){struct node* nextNode = freeNode->next;free(freeNode);freeNode = nextNode;}}free(hashSet->bucket);free(hashSet);
}bool isCycle(struct ListNode* head)
{struct hashSet* hashSet = hashSetInit(512);struct ListNode* curNode = head;bool is = false;while (curNode){if (hashSetFind(hashSet, curNode)){is = true;break;}hashSetInsert(hashSet, curNode);curNode = curNode->next;}hashSetFree(hashSet);return is;
}bool hasCycle(struct ListNode* head)
{return isCycle(head);
}
解法二:快慢指针
bool isCycle(struct ListNode* head)
{struct ListNode* fast = head;struct ListNode* slow = head;while (fast && fast->next){fast = fast->next->next;slow = slow->next;if (fast == slow)return true;}return false;
}bool hasCycle(struct ListNode* head)
{return isCycle(head);
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/250334.html
如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!