判断单循环链表中是否存在环
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; }
相关文章推荐
- Mybatis原理学习1:从JDBC过渡到Mybatis
- 1050. String Subtraction (20)
- vim 比较文件、修改二进制文件
- 关于视差滚动
- D10
- 欢迎使用CSDN-markdown编辑器
- android.os.NetworkOnMainThreadException 异常处理
- 5、Mybatis-Spring入门
- Spring MVC 教程,快速入门,深入分析(转)
- 第一次作业——四则运算小程序
- 仿Android5.0 水波扩散效果(Ripple)简单实现
- HTML5本地存储Localstorage
- 计算机中数的表示
- Find the kth largest element in an unsorted array
- 分解质因数
- ZOJ 1100 Mondriaan's Dream
- 如何通过变量去调用对应的函数
- 逻辑回归的实现
- 单循环链表(使用尾指针表示)
- 4、动态Sql