/*判斷單鏈表中是否有環*/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;}