题目链接
题目描述
示例
示例1:
输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。
提示
- 链表中节点的数目范围是
[0, 10] -10 <= Node.val <= 10-
思路
思路1:哈希表
使用哈希表保存所有访问过的结点,每遍历一个结点,判断该结点是否在哈希表中,如果在表示有环。
思路2:快慢指针
设两个指针
slow和fast,slow每次移动一个结点,fast每次移动两个结点,如果链表中有环,那么fast会提前进入换环中,等到slow进入环后,fast总会追上slow,即俗说的套圈。题解
思路2:快慢指针
/*** 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* slow = head;ListNode* fast = head;while (fast != nullptr && fast->next != nullptr) {slow = slow->next;fast = fast->next->next;if (slow == fast) {return true;}}return false;}};
复杂度分析
时间复杂度:
- 空间复杂度:
