欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

循环链表的基本操作

程序员文章站 2024-03-21 19:46:58
...
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>
using namespace std;


typedef int dataType;


typedef struct Node{
	dataType data;
	struct Node *next;
}CLListNode;
typedef CLListNode *pCLList;


//使用尾插法,创建一个循环链表
pCLList CreateLinkList_1_9_order()
{
	pCLList head=(CLListNode*)malloc(sizeof(CLListNode));
	head->next=NULL;
	CLListNode *p=NULL;
	CLListNode *r=head;
	int num=9,i=1;
	while (i<=num)
	{
		p=(CLListNode*)malloc(sizeof(CLListNode));
		p->data=i;
		r->next=p;
		r=p;
		i++;
	}
	r->next=head;
	return head;
}


//输出循环链表
void OutPut(pCLList l)
{
	CLListNode *p=l->next;
	cout<<"LinkList:";
	while(p!=l)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl<<endl;
}


//释放循环链表内存
void FreeCLinkList(pCLList *l)  //传入pCLList二级指针
{
	CLListNode *p=(*l)->next,*temp;  //定义移动指针p,初始化为头指针,指向头结点
	free(*l);
	while (p!=*l)
	{
		temp=p;
		p=p->next;
		free(temp);
	}
	*l=NULL;
}


//获取链表长度
int GetLListLength(pCLList l)
{
	CLListNode *p=l->next;
	int i=0;
	while (p!=l)
	{
		i++;
		p=p->next;
	}
	return i;
}


//连接两个循环链表
void ConnectTwoCLList(pCLList a,pCLList b)
{
	CLListNode *pa=a->next,*pb=b->next,*temp=b;
	while(pa->next!=a)
	{
		pa=pa->next;
	}
	pa->next=b->next;
	free(temp);
	while (pb->next!=b)
	{
		pb=pb->next;
	}
	pb->next=a;
}


int main()
{
	pCLList a=CreateLinkList_1_9_order();
	OutPut(a);
	pCLList b=CreateLinkList_1_9_order();
	OutPut(b);


	ConnectTwoCLList(a,b);
	OutPut(a);


	b=NULL;
	FreeCLinkList(&a);
	system("pause");
	return 1;
}

相关标签: 循环链表