循环链表的概念:
循环链表是另一种形式的链式存贮结构。它的特点是表中最后一个结点的指针域指向头结点,整个链表形成一个环。
示意图:
代码实现:
clist.h
#pragma once
//循环链表
typedef struct CNode
{
int data;
struct CNode *next;
}CNode,*CList;
//循环链表初始化
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);
//获取循环链表长度(数据结点的个数)
int GetLength(CList plist);
//判空
bool IsEmpty(CList plist);
//清空
void Clear(CList plist);
//摧毁
void Destroy(CList plist);
//打印循环链表
void Show(CList plist);
clist.cpp
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include"clist.h"
//循环链表初始化
void InitList(CList plist)
{
assert(plist != NULL);
if(plist == NULL)
{
return ;
}
plist->next = plist;
}
//头插
bool Insert_head(CList plist,int val)
{
assert(plist != NULL);
if(assert == NULL)
{
return false;
}
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)
{
assert(plist != NULL);
if(assert == NULL)
{
return false;
}
CNode* p = (CNode*)malloc(sizeof(CNode));
p->data = val;
NCode*q;
//找尾巴
for(q= plist; q->plist != plist; q= q->next)
//将p插在q后面
q->next = p;
p->next = plist;
return true;
}
//查找
CNode *Search(CList plist,int key)
{
assert(plist != NULL);
if(plist == NULL)
{
return false;
}
for(CNode *p = plist->next;p != plist;p = p->next)
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
//删除
bool Delete(CList plist,int key)
{
assert(plist != NULL);
if(plist == NULL)
{
return false;
}
CNode *p = SearchPri(plist,key);
if(p == NULL)
{
return false;
}
CNode *q = p->next;
p->next = q->next;
free(q);
return true;
}
//获取循环链表长度(数据结点的个数)
int GetLength(CList plist)
{
int count = 0;
for(CNode *p = plist->next;p != plist;p = p->next)//遍历所有结点
{
count++;
}
return count;
}
//判空
bool IsEmpty(CList plist)
{
return plist->next = plist;
}
//清空
void Clear(CList plist)
{
Destroy(plist);
}
//摧毁
void Destroy(CList plist)
{
CNode*p;
while(p->next != plist)
{
p = plist->next;
plist->next = p->next;
free(p);
}
}
//打印循环链表
void Show(CList plist)
{
CNode* p
for(p= plist->next;p !=plist;p = p->next )
{
printf("%d",p->data);
}
printf("\n");
}
主函数:
#include<stdio.h>
#include<vld.h>//测试内存是否泄露
#include"clist.h"
int main()
{
CNode head1;
CNode head2;
//测试初始化
InitList(&head1);
InitList(&head2);
for(int i = 0;i < 15;i++)
{
Insert_head(&head1,i);
Insert_tail(&head2,i);
}
Show(&head1);
Show(&head2);
//测试删除
Delete(&head2,6);
Show(&head2);
//测试获取单向循环链表的长度
printf("%d\n",GetLength(&head1));
//测试摧毁
Destroy(&head1);
Destroy(&head1);
return 0;
}