算法思想:在建立循環鏈表時設置兩個指針,頭指針和尾指針,head和tail,使tail->next=head,即讓尾節點指向頭節點,建立的時候采用尾插入法,每次讓新節點先指向尾節點的下一個節點,
然后讓頭節點的下一個節點指向新節點,然后讓新節點賦值給頭節點和尾節點。
判斷是否是循環鏈表時,也設置兩個指針,慢指針和快指針,讓快指針比慢指針每次移動快兩次。如果快指針追趕上慢指針,則為循環鏈表,否則不是循環鏈表,如果快指針或者慢指針指向NULL,則不是循環鏈表。
include <iostream> #include <cstdlib> using namespace std; typedef struct list { int data; struct list *next; }loopNode,*lpNode; void createList(lpNode &list,int arr[],int n) //創建循環鏈表 { lpNode node; lpNode head=NULL,tail=NULL; head=tail=list; tail->next=head; for(int i=0;i<n;i++) { node=(struct list*)malloc(sizeof(struct list)); node->data=arr[i]; node->next=tail->next; head->next=node; head=node; tail=node; } cout<<"create success"<<endl; } int judgeIsLoop(lpNode list) //判斷是否是循環鏈表 { if(list==NULL) return 0; lpNode slow,fast; slow=list; fast=list->next->next; while(slow) { if(fast==NULL||fast->next==NULL) return 0; else if(fast==slow||fast->next==slow) return 1; else { slow=slow->next; fast=fast->next->next; } } return 0; } void display(lpNode list) //輸出循環鏈表 { lpNode head,tail; head=tail=list; while(head->next!=tail) { cout<<head->data<<"--"; head=head->next; } cout<<head->data; cout<<endl; } int main() { lpNode list=NULL; int arr[10]={1,2,3,4,5,6,7,8,9,0}; int flag=0; list=(struct list*)malloc(sizeof(struct list)); list->data=11; list->next=NULL; createList(list,arr,10); flag= judgeIsLoop(list); if(flag==1) //如果是循環鏈表,就輸出循環鏈表 { cout<<"the list is loop list."<<endl; cout<<"output the list:"<<endl; display(list); } else { cout<<"the list is not loop list."<<endl; } cout<<endl; return 0; }
運行截圖: