循环链表

循环列表

单链表的尾巴的下一个结点为头结点时,该链表称为循环列表。

下来我们结合图和代码来理解一下:

创建循环链表:

void init_LA(CircleLinkList *L){//尾插法
	L->data=0;
	L->next=L;
	for(int i=1;i<=10;i++){
		Node *n=malloc(sizeof(Node));
		n->data=i;
		if(i==1){
			RA=n;
		}
		n->next=L->next;
		L->next=n;
		L->data++;
	}
}

合并循环链表:

void combine(CircleLinkList *LA,CircleLinkList *LB){//链表合并
	RA->next=LB->next;
	RB->next=LA;
	RA=RB;
	LA->data+=LB->data;
	free(LB);
}

 

判断单链表是否为循环链表:

1、快慢指针

2、A一直往前走,B每次都从头走,A一共走了几步,B最大走几步,如果步数不同,但值相同,出环

我们来看这两种方法:

#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct Node{
	ElemType data;
	struct Node *next;
}Node,CircleLinkList;
Node *R;
void init(CircleLinkList *L){
	L->data=0;
	L->next=L;
	R=L;
	Node *C;//循环点
	for(int i=1;i<=10;i++){
		Node *n=malloc(sizeof(Node));
		if(i==3){
			C=n;
		}
		n->data=i;
		n->next=R->next;
		R->next=n;
		R=n;
	}
	R->next=C;
}
void show(CircleLinkList *L){
	Node *p=L;
	printf("[");
	while(1){
		p=p->next;
		if(p==R){
			printf("%d]\n",p->data);
			break;
		}else{
			printf("%d,",p->data);
		}
	}
}
void hasLoop_A(CircleLinkList *L){//只能判断是否为循环链表
	Node *A=L;
	Node *B=L;
	while(A->next!=B->next->next){
		A=A->next;
		B=B->next->next;
	}
	printf("有环!\n");
}
void hasLoop_B(CircleLinkList *L){//能判断,还能找出来出环点
	Node *A=L;
	Node *B;
	int count=0;
	while(1){
		A=A->next;
		count++;
		B=L;
		for(int i=0;i<count;i++){
			B=B->next;
			if(A->data==B->data&&count!=i){
				printf("有环!%d\n",B->data);
				return ;
			}
		}
	}
}
void main(){
	CircleLinkList L;
	init(&L);
	show(&L);	
	hasLoop_A(&L);
	//hasLoop_B(&L);
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值