Description:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution:
题意:给定一个链表,判断是否存在环路。
思路:
第一种方法:使用哈希表存储查询,但需要消耗空间。
第二种方法:使用两个指针遍历链表,一个快(一次迭代移两个节点),一个慢(一次迭代移一个节点),若快指针指向了NULL,则没有循环。若两指针重合,则存在循环。
为什么两指针会重合?
Case 1:快指针在慢指针指向的上一个节点,那么下一次迭代两者将重合。
Case 2:快指针在慢指针指向的上两个或以上节点,那么下一次或下几次迭代两者状态将成为Case 1.
因此两指针会重合。
Marvelous!!
/**
* 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)
return false;
// Marvelous!!
// slow pointer move 1 step each loop
// fast pointer move 2 step each loop
// if it has a cycle, they must meet each other in several loops
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
return true;
}
return false;
}
};