Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个单链表里是否有循环,这个问题以前在一本书上见过,具体思路是这样的:
定义两个节点,都从头开始,一个每次走两步,另一个每次走一步,如果有循环,那么这两个节点肯定会相遇。
具体代码如下:
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)return false;
ListNode *tmpFast = head;
ListNode *tmpSlow = head;
do
{
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast==NULL)
return false;
tmpSlow = tmpSlow->next;
} while (tmpFast != tmpSlow);
return true;
}
};
void main()
{
ListNode *a = new ListNode(3);
a->next = a;
/*a->next = new ListNode(2);
a->next->next = new ListNode(0);
a->next->next->next = new ListNode(-4);
a->next->next->next->next = a->next;*/
Solution s;
bool cycle = s.hasCycle(a);
while(1);
}