一、概述
从上图看出循环链表有两个成员:data 和 next
由此可创建循环链表和它的一些基本操作如下:
注明:它的操作其实与单链的操作差不多,只要注意判断标志即可。
#pragma once
//循环链表,尾节点的next指向头
typedef struct CNode //宏定义
{
int data;
struct CNode *next;
}CNode,*CList;//CList==CNode*
void InitList(CList plist);
//头插
bool Insert_head(CList plist,int val);
//尾插
bool Insert_tail(CList plist,int val);
CNode *Search(CList plist,int key);
bool Delete(CList plist,int key);
bool IsEmpty(CList plist);
int GetLength(CList plist);
void Show(CList plist);
void Destroy(CList plist);
void Clear(CList plist);
链表操作实现:
void InitList(CList plist)
{
assert(plist != NULL);
plist->next = plist;
}
//头插
bool Insert_head(CList plist,int val)
{
CNode *p = (CNode *)malloc(sizeof(CNode));//创建新节点
p->data = val;
p->next = plist->next;//连线,防止数据丢失
plist->next = p;
return true;
}
//尾插
bool Insert_tail(CList plist,int val)
{
CNode *p = (CNode *)malloc(sizeof(CNode));
p->data = val;
CNode *q;
for(q=plist;q->next!=plist;q=q->next) ;//->next==NULL
//将p插入在q后面
p->next = q->next;
q->next = p;
return true;
}
CNode *Search(CList plist,int key)
{
CNode *p;
for( p = plist;plist->next != plist;p=p->next)//遍历找key,注意链表的有效数据节点既是它的头,也是尾。
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
bool Delete(CList plist,int key)
{
CNode *p;
for(p=plist;p->next!=plist;p=p->next)
{
if(p->next->data == key)//找到key的上一个节点位置
{
break;
}
}
if(p->next == plist)//没有key
{
return false;
}//将节点从链表中删除
CNode *q = p->next;
p->next = q->next;
//p->next = p->next->next;
free(q);//释放内存
return true;
}
bool IsEmpty(CList plist)
{
return plist->next == NULL;
}
int GetLength(CList plist)
{
int count = 0;//计数器
for(CNode *p = plist;p->next != plist;p=p->next)
{
count++;
}
return count;
}
void Destroy(CList plist)
{
CNode *p;
while(plist->next != plist)
{
p = plist->next;
plist->next = p->next;
free(p);
}
}
void Clear(CList plist)
{
Destroy( plist);
}
void Show(CList plist)
{
CNode *q;
for(q=plist->next; q->next !=plist;q=q->next)
{
printf("%d ",q->data);
}
}
程序测试:
#include<stdio.h>
#include<stdlib.h>
#include<vld.h>
#include"clist.h"//循环链表已完成
int main()
{
CNode sa;
InitList(&sa);
int i;
for(i=0;i<10;i++)
{
Insert_tail(&sa,i);
}
//printf("%d ",Search(&sa,100));
Delete(&sa,2);
Delete(&sa,3);
Delete(&sa,12);
printf("%d\n",GetLength(&sa));
//Destroy(&sa);
//Destroy(&sa);
//Destroy(&sa);
Show(&sa);
return 0;
}
运行结果: