【LeetCode】141. Linked List Cycle (2 solutions)

2023-03-15,,

Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

解法一:

使用unordered_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*, bool> visited;
while(head != NULL)
{
if(visited[head] == true)
return true;
visited[head] = true;
head = head->next;
}
return false;
}
};

解法二:不使用额外空间

设置快慢指针,

fast每次前进两步,slow每次前进一步,如相遇说明有环,如到达尾部说明无环。

/**
* 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;
ListNode* slow = head;
do
{
if(fast != NULL)
fast = fast->next;
else
return false;
if(fast != NULL)
fast = fast->next;
else
return false;
slow = slow->next;
}while(fast != slow);
return true;
}
};

【LeetCode】141. Linked List Cycle (2 solutions)的相关教程结束。

《【LeetCode】141. Linked List Cycle (2 solutions).doc》

下载本文的Word格式文档,以方便收藏与打印。