// ListIsLoop.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
//6、判断一个链表是否有循环。
struct List
{
List(char* name)
{
strcpy(this->name,name);
next=NULL;
}
List* Append(List* other)
{
//if (!other)return NULL;//允许后面接NULL
this->next=other;
return other;
}
char name[256];
List* next;
};
bool isLoop(List* l) {
if ( ! l)
return false ;
List* s = l->next;
while (s && s != l)//如果有循环,会回到l
{
s = s->next;
}
if ( ! s)//如果没有循环,会走到NULL
return false;
else
return true ;
}
//-----------
/*
int isLoop(List l){
if(!l)
return 0;
p=l.next;
wihle(p!=l&&p!=null)
{
l.next=l;//将next 指针指向自身【破坏了原始结构】
l=p;
p=p.next;
}
if(p=l) return 1;
return 0;
}
//*/
/*
实际上,在我的面试过程中,还问到了不破坏结构的其他算法。
我的答案是从链表头开始遍历,如果节点next 指针指向自身,则循环存在;
否则将next 指针
指向自身【破坏了原始结构】,遍历下一个节点。直至next 指针为空,此时链表无循环。
*/
int main(int argc, char* argv[])
{
List * zhang=new List("zhang");
List * wang=zhang->Append(new List("wang"));
List * li=wang->Append(new List("li"));
List * zhao=li->Append(new List("zhao"));
if(isLoop(zhang))
printf("1st:Loop!\n");
zhao->Append(zhang);
if(isLoop(zhang))
printf("2nd:Loop!\n");
return 0;
}
/*
2nd:Loop!
Press any key to continue
*/