단일 순환 체인 테이블에 링이 존재하는지 판단

#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
"); exit(1); } (*L)->next = NULL; } void CreateSimpleCycleList_withoutLoop(LinkList *L,int number){ int count; LinkList new,tail = (*L); printf("Create SimpleCycleList_withoutLoop
"); for(count = 1;count <= number; count++){ new = (LinkList)malloc(sizeof(struct Node)); if(!(new)){ printf("Error:CreateSimpleCycleList_withoutLoop
"); 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
"); } else{ printf("Create SimpleCycleList_withLoop
"); for(count = 1; count <= number; count++){ new = (LinkList)malloc(sizeof(struct Node)); if(!new){ printf("Error:CreateSimpleCycleList_withLoop
"); 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
",step_i); else printf("Dose no Exist loop in this List!
"); } 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.
"); else printf("Dose no Exist loop in this List!
"); } void Display_withoutLoop(LinkList L){ while(L->next != NULL){ L = L->next; printf("%d ",L->data); } printf("
"); } 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; }

좋은 웹페이지 즐겨찾기