Linked List Cycle

来源:互联网 发布:淘宝代销怎么样 编辑:程序博客网 时间:2024/06/15 04:50

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);
}

0 0
原创粉丝点击