Analyzing circular list (how pointers C application speed) ------- algorithm 004 Notes

concept

Here Insert Picture Description

Determining whether the speed of the linked list has a pointer ring

Bool ifLoopOfList(List head){
	List quick=NULL;
	List slow=NULL;
	quick=slow=head;
	
	do{
		quick=quick->next->next;
		slow=slow->next;
		printf("quick->%d\tslow->%d\n",quick->data,slow->data);
		if(quick==slow){
			return 1;
		}
		
	}while(quick);
	
	return 0;
	
}

Project Files

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
	int data;
	struct node *next;
}Node,*List;
typedef int Bool; 
List createLoopList(List head,int num,int loopSpot/*定义尾部的指向*/);
Bool ifLoopOfList(List head);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

/**
	判断链表是否有环这里用性能最优的快慢指针来实现
	 
*/ 

int main(int argc, char *argv[]) {
	List head=(List)malloc(sizeof(Node));
	List ret=createLoopList(head,10,3/*定义尾部的指向*/);
	if(ifLoopOfList(ret)){
		printf("有环链表");
	}else{
		printf("无环链表");		
	}
	printf("\n");
	getchar(); 
	return 0;
}

Bool ifLoopOfList(List head){
	List quick=NULL;
	List slow=NULL;
	quick=slow=head;
	
	do{
		quick=quick->next->next;
		slow=slow->next;
		printf("quick->%d\tslow->%d\n",quick->data,slow->data);
		if(quick==slow){
			return 1;
		}
		
	}while(quick);
	
	return 0;
	
}

List createLoopList(List head,int num,int loopSpot/*定义尾部的指向*/){
	//尾插法
	int i=1;
	List p=head;
	List q=head;
	while(num--){
		List new =(List)malloc(sizeof(Node));
		new->data=i++;
		p->next=new;
		p=new; 
	} 
	/*
	无环链表的创建 
	p->next=NULL; 
	p=head->next;
	*/
	
	for(i=0;i<loopSpot;i++){
		q=q->next;
	}
	p->next=q;
	q=head->next;
	free(head);
	return q;	 
}





Published 32 original articles · won praise 0 · Views 723

Guess you like

Origin blog.csdn.net/qq_35392733/article/details/104081031