问题描述
Given a linked list, determine if it has a cycle in it.Follow up:
Can you solve it without using extra space?解决思路
开两个指针,一个每次走一步,一个每次走两步,看它们是否会重合。代码
/**
* 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;
ListNode *walk = head, *run = head;
while(walk->next != NULL && run->next != NULL && run->next->next != NULL) {
walk = walk->next;
run = run->next->next;
if (walk == run)
return true;
}
return false;
}
};