/*判断单链表中是否有环*/
struct ListType
{
int data;
struct ListType *next;
};
typedef struct ListType *list;
int IsLoop(list s)
{//双指针法
list fast = s;
list slow = s;
if(fast == NULL)
return -1;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return 1;
}
return !(fast == NULL) || (fast->next == NULL);
}
#include<map>
using std::map;
typedef struct node
{
int data;
struct node *next;
}node;
map<node*,int>m;
bool IsLoop(node *head)
{//hash表法
if(!head)
{
return false;
}
node *p = head;
while(p)
{
if(m[p] == 0) //默认都是0
{
m[p] = 1;
}
else if(m[p] == 1)
return true;
p = p->next;
}
}
list *FindLoopPort(list *head)
{//寻找入口点
list *slow = head,*fast = head;
while(fast && fast->next)
{//寻找相遇点
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
break;
}
if(fast == NULL || fast->next == NULL)
return NULL;
slow = head;
while(slow != fast)
{//slow指针从起点开始走,fast指针从相遇点开始走,俩指针相遇处即为环的入口点
slow = slow->next;
fast = fast->next;
}
return slow;
}