题目描述:
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. Ifpos
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.
题目看起来不是很复杂,属于一般的链表问题。即给一个链表判断它是否内部存在小循环,pos在所写的成员函数中并没有写出,只给出链表,实际上pos代表的意义是开始发生循环的在链表的位置,只是为了描述问题的方便,毕竟循环链表没办法表示,所以可以忽略,只要有所给的链表进行判断即可,不必考虑。
考虑使用快指针和慢指针的双指针的方法, 即一个指针每次走一步,跳到next上,而另一个指针每次走两步,跳到next->next上,这样当有循环时,两个指针迟早会指向一个node结点上,即两个指针相同(指针的地址相同),快指针可以走3步甚至多步都可以,我们采用2步的方法;当没有循环时快指针,或者快指针的next会探测到链表的终点NULL(c++中用大写的NULL来表示),这样即可解决问题。
这个方法非常巧妙,100%的速度,代码为:
/**
* 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) {
if(!head || !head->next)
return false;
ListNode* slow = head;
ListNode* fast = head->next;
while(slow != fast)
{
if(!fast || !fast->next)
{
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};