Linux下实现循环链表的基本操作

循环连链表的定义
对于循环链表的定义和操作的图形表示在上述文章中讲述的已经很明白 ,这里就不在追赘述,在找代码测试时,发现有的代码不是很全,于是就自己尝试整合了一些代码,以供日后学习!

在这#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
typedef int dataType;
typedef struct Node{
dataType data;
struct Node *next;
}CLListNode;
typedef CLListNode *pCLList;
//使用尾插法创建一个循环链表
pCLList CreateLinkList(){
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){
CLListNode *p=(*l)->next;
CLListNode *temp;
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;
}
//从头部插入元素
bool Insert_head(pCLList l,int val){
CLListNode *p=(CLListNode*)malloc(sizeof(CLListNode));
p->data=val;
p->next=l->next;
l->next=p;
return true;
}
//从尾部插入元素
bool Insert_tail(pCLList l,int val){
CLListNode *p=(CLListNode*)malloc(sizeof(CLListNode));
p->data=val;
CLListNode *q;
for(q=l;q->next!=l;q=q->next);//此时的q指向尾部
p->next=q->next;
q->next=p;
return true;
}
CLListNode *Search(pCLList l,int key){
CLListNode *p;
for(p=l;l->next!=l;p=p->next){
if(p->data==key){
return p;
}
}
return NULL;
}
bool Delete(pCLList l,int key){
CLListNode *p;
for(p=l;p->next!=l;p=p->next){
if(p->next->data==key){
break;
}
}
if(p->next==l){
return false;
}
CLListNode *q=p->next;
p->next=q->next;
free(q);
return true;
}
bool IsEmpty(pCLList plist){
return plist->next==NULL;
}
//连接两个循环列表
void ConnectTwoCLList(pCLList a,pCLList b){
CLListNode *pa=a->next;
CLListNode *pb=b->next;
CLListNode *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();
OutPut(a);
Insert_tail(a,100);
OutPut(a);

pCLList b=CreateLinkList();
Insert_head(b,200);
OutPut(b);
Delete(b,8);
OutPut(b);
//ConnectTwoCLList(a,b);
//OutPut(a);

b=NULL;
FreeCLinkList(&a);
return 0;

}
里插入代码片
亲测可用!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值