Given a linked list, determine if it has a cycle in it.
// Two pointers chasing each other.
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
if(slow == fast) return true;
}
return false;
}
A Cycle means that the address will be visited twice.
bool hasCycle(ListNode *head) {
if(!head) return false;
set<ListNode*> address;
ListNode* slow = head;
while(slow) {
if(address.find(slow) != address.end()) return true;
address.insert(slow);
slow = slow->next;
}
return false;
}
本文介绍两种有效的方法来判断链表中是否存在循环:一种是使用快慢指针技术,通过两个速度不同的指针在链表中前进,如果存在循环则两指针最终会相遇;另一种方法则是借助哈希集合,遍历链表并将每个节点地址存入哈希集合中,如果某个节点地址已存在于集合中,则说明链表中存在循环。
822

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



