Is a loop ? Question descrip as follows :node
Assume that wehave a head pointer to a link-list. Also assumethat we know the list is single-linked. Can you come up an algorithm to checkwhether this link list includes a loop by using O(n) time and O(1) space wheren is the length of the list? Furthermore, can you do so with O(n) time and onlyone register?ios
/******************************************************************** created:2015年1月22日 00:54:56 author: Jackery purpose: Is there a loop ? *********************************************************************/ #include"stdafx.h" #include<iostream> using namespace std; typedef struct node { int data; struct node *next; }Node,*pNode; Node *Create(int *numNode) { //建立一個鏈表 Node *head,*tail,*cnew; head=NULL; int num; cout <<"輸入數據(以#鍵結束):" << endl; while(1 ) { cin >>num ; if('#'==getchar()) //以#鍵表示輸入結束 break; cnew=new Node;; cnew->data=num; cnew->next=NULL; if(head==NULL) //若爲空則將頭節點指向新節點 head=cnew; else tail->next=cnew; //將當前節點的next指向新的節點 tail=cnew; (*numNode)++; } return head;} /*判斷是否有環思路概述:分別定義步長爲1和2的指針fast and slow 指向頭結點,if無環,則fast先走到終點;若是鏈表長度爲奇數時, fast->Next爲空;當鏈表長度爲偶數時,fast爲空*/ bool isLoop(pNode pHead) { pNode fast = pHead; pNode slow = pHead; while( fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; //若是有環,則fast會超過slow一圈 if(fast == slow) { break; } } if(fast == NULL || fast->next == NULL ) { cout <<"Wow,there is not loop in the list "<< endl; return false; } else { cout <<"Yeah,there is loop in the list " << endl; return true; } } int main(int argc ,char * argv[]) { int numnode=0; //初始化將節點個數初始化爲零 pNode head=NULL ; cout <<"鏈表head的節點個數爲: " <<endl; cin >>numnode; head=Create(&numnode); isLoop(head); return 0; }