循环链表是另一种形式的链式储存结构
特点: 表中的最后一个结点的指针域指向头结点,整个链表形成一个环
clist.h
#pragma once
//循环链表,尾节点next保存头节点的地址
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);
bool IsEmpty(CList plist);
//获取长度,数据个数
int GetLength(CList plist);
void Show(CList plist);
//获得key的前驱
CNode *GetPrio(CList plist,int key);
//获取key后继
CNode *GetNext(CList plist,int key);
//清空数据
void Clear(CList plist);
//销毁
void Destroy(CList plist);
clist.cpp
#include"pch.h"
#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)
{
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;
for (p = plist; p->next != plist; p = p->next);
CNode *q = ( CNode * )malloc(sizeof(CNode));
q->data = val;
//q插入在p的后面
q->next = p->next;
p->next = q;
return true;
}
//查找
CNode *Search(CList plist, int key)
{
for (CNode *p = plist->next; p != plist; p = p->next)
{
if (p->data == key)
{
return p;
}
}
return NULL;
}
//删除
bool Delete(CList plist, int key)
{
CNode *p = GetPrio(plist, key);
if (p == NULL)
{
return false;
}
CNode *q = p->next;//
p->next = q->next;
free(q);
return true;
}
bool IsEmpty(CList plist)
{
return plist->next == plist;
}
//获取长度,数据个数
int GetLength(CList plist)
{
int count = 0;
for (CNode *p = plist->next; p != plist; p = p->next)
{
count++;
}
return count;
}
void Show(CList plist)
{
for (CNode *p = plist->next; p != plist; p = p->next)
{
printf("%d ", p->data);
}
printf("\n");
}
//获得key的前驱
CNode *GetPrio(CList plist, int key)
{
for (CNode *p = plist; p->next != plist; p = p->next)
{
if (p->next->data == key)
{
return p;
}
}
return NULL;
}
//获取key后继
CNode *GetNext(CList plist, int key)
{
CNode *p = Search(plist, key);
if (p == NULL || p->next == plist)
{
return NULL;
}
return p->next;
}
//清空数据
void Clear(CList plist)
{
Destroy(plist);
}
//销毁
void Destroy(CList plist)
{//删除第一个
CNode *p;
while (plist->next != plist)
{
p = plist->next;
plist->next = p->next;
free(p);
}
}