寫一段代碼判斷一個單向鏈表中是否有環。
struct node { int data; node *next; }*linklist,*s,*t;
#include "iostream" #include "map" using namespace std; map<node*,int>m; bool IsLoop(node *head) { 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; } }
思路:
用兩個指針,pSlow,pFast,就是一個慢一個快
慢的一次跳一步
快的一次跳兩步
往鏈表末端移動。如果pFast==NULL,則說明鏈表沒有環,如果pSlow==pFast,則說明鏈表存在環。
bool IsLoop(node *head) { node *pSlow=head; node *pFast=head; while(pSlow!=NULL && pFast!=NULL) { pSlow=pSlow->next; pFast=pFast->next->next; if(pSlow==pFast) return true; } return false; }
#include "iostream" #include "map" using namespace std; struct node { int data; struct node *next; }*linklist,*s,*head; map<node*,int>m; bool IsLoop(node *head) { node *pSlow=head; node *pFast=head; while(pSlow!=NULL && pFast!=NULL) { pSlow=pSlow->next; pFast=pFast->next->next; if(pSlow==pFast) return true; } return false; } node* InsertNode(node *head,int value) { if(head==NULL) { head=(node *)malloc(sizeof(node)); if(head==NULL) printf("malloc failed"); else { head->data=value; head->next=NULL; } } else { node *temp=(node *)malloc(sizeof(node)); if(temp==NULL) printf("malloc failed"); else { temp->data=value; temp->next=head; head=temp; } } return head; } int main(void) { node *t,*q,*p=NULL; p=InsertNode(p,8); p=InsertNode(p,7); p=InsertNode(p,6); p=InsertNode(p,5); p=InsertNode(p,4); q=p; p=InsertNode(p,3); p=InsertNode(p,2); p=InsertNode(p,1); t=p; while(t->next) // 找到鏈表的尾指針 t=t->next; t->next=q; // 將鏈表的尾指針指向第四個節點,這樣就構成了一個環 bool flag=IsLoop(p); if(flag) cout<<"這個鏈表存在一個環"<<endl; else cout<<"這個鏈表不存在一個環"<<endl; system("pause"); return 0; }