题目
level:easy
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
解题思路
想象有两个指针,一个指针每次只往后移动一个节点,另一个指针每次往后移动两个节点,若节点能形成环,则这两个指针在移动过程中必定会重合;
- 声明两个指针,一个指针每次移动一个节点,另一个指针每次移动两个节点;
- 当遇到NULL时,必定不成环;若遍历过程中两节点相遇,则必定成环。
算法实现(C++)
/**
1. Definition for singly-linked list.
2. struct ListNode {
3. int val;
4. ListNode *next;
5. ListNode(int x) : val(x), next(NULL) {}
6. };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head)
return false;
ListNode* oneNode = head;//该指针每次只往后移动一个节点
ListNode* twoNode = head->next;//该指针每次往后移动两个节点
while (oneNode && twoNode && twoNode->next)
{
if (oneNode == twoNode)
return true;
oneNode = oneNode->next;
twoNode = twoNode->next->next;
}
//程序运行至此,则说明退出了while循环,说明上述节点有NULL存在,则必定不成环
return false;
}
};
复杂度分析
- 时间复杂度:O(n),当链表不成环时,节点遍历到NULL则结束;当链表成环时,则在成环节点的有限圈数内两指针必定相遇;
- 空间复杂度:O(1),只需有限的两个指针即可。