您的位置:首页 > 其它

判断单循环链表中是否存在环

2016-03-11 22:32 323 查看
#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
int data;
struct Node* next;
}Node;
typedef struct Node* LinkList;

void InitialLinkList(LinkList *L){
(*L) = (LinkList)malloc(sizeof(struct Node));
if(!(*L)){
printf("Error:InitialLinkList:malloc\n");
exit(1);
}
(*L)->next = NULL;
}
void CreateSimpleCycleList_withoutLoop(LinkList *L,int number){
int count;
LinkList new,tail = (*L);
printf("Create SimpleCycleList_withoutLoop\n");
for(count = 1;count <= number; count++){
new = (LinkList)malloc(sizeof(struct Node));
if(!(new)){
printf("Error:CreateSimpleCycleList_withoutLoop\n");
exit(1);
}
printf("please enter %d element:  ",count);
scanf("%d",&(new->data));
new->next = tail->next;
tail->next = new;
tail = new;
}
}
void CreateSimpleCycleList_withLoop(LinkList *L,int number,int loopInIndex){
/* 第一个参数LinkList是要创建的有环的链表
* 第二个参数number是链表的长度
* 第三个参数loopInIndex是指示环由链表的末尾指向了第几个元素,0则表示是指向了头结点。
* */
int count;
LinkList new,temp = *L,temp1 = *L;
if(loopInIndex > number){
printf("Error:CreateSimpleCycleList_withLoop:loopInIndex\n");
}
else{
printf("Create SimpleCycleList_withLoop\n");
for(count = 1; count <= number; count++){
new = (LinkList)malloc(sizeof(struct Node));
if(!new){
printf("Error:CreateSimpleCycleList_withLoop\n");
exit(1);
}
printf("please enter %d element  ",count);
scanf("%d",&(new->data));
temp->next = new;
new->next = *L;
temp = new;
}
for(count = 0;count < loopInIndex; count++){
temp1 = temp1->next;
}
temp->next = temp1;
}
}
void JodgeLoop(LinkList L){
LinkList p = L,q = L;
int step_o = 0,step_i = 0;
int isLoop = 0;
while(p){
step_i = 0;
q = L;
while(q != p){
q = q->next;
step_i++;
}
if(step_o != step_i){
isLoop = 1;
break;
}
p = p->next;
step_o++;
}
if(isLoop == 1)
printf("Exist loop in this List.Appear in position %d\n",step_i);
else
printf("Dose no Exist loop in this List!\n");
}
void JodgeLoop_2(LinkList L){
LinkList quick = L,slow = L;
int isLoop = 0;
while(quick != NULL && quick->next != NULL){
quick = quick->next->next;
slow = slow->next;
if(quick == slow){
isLoop = 1;
break;
}
}
if(isLoop)
printf("Exist loop in this List.\n");
else
printf("Dose no Exist loop in this List!\n");
}
void Display_withoutLoop(LinkList L){
while(L->next != NULL){
L = L->next;
printf("%d ",L->data);
}
printf("\n");
}

int main(){
LinkList L1;
LinkList L2;
InitialLinkList(&L1);
InitialLinkList(&L2);
CreateSimpleCycleList_withLoop(&L1,5,1);
CreateSimpleCycleList_withoutLoop(&L2,4);
JodgeLoop(L1);
JodgeLoop(L2);
JodgeLoop_2(L1);
JodgeLoop_2(L2);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: