clist.h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//#include <vld.h>
//千万不要使用头结点进行查找或比较等
typedef struct CNode
{
int data;
struct CNode *next;
}CNode,*CList;
void InitCList(CList plist);
void Insert_Chead(CList plist,int val);
void Insert_Ctail(CList plist,int val);
bool Delete(CList plist,int key);
void ShowC(CList plist);
int GetlengthC(CList plist);
CNode * Search(CList plist,int key);
void Destroy(CList plist);
clist.cpp
#include "clist.h"
//static:只能本文件使用
//修饰函数,全局变量,局部变量(生命周期从创建时到程序退出)
//初始化循环链表
void InitCList(CList plist)
{
assert(plist->next!=NULL);
plist->next=plist;
}
//申请一个结点
static CNode * BuyCNode(int val)
{
CNode *p=(CNode *)malloc(sizeof(CNode));
assert(p!=NULL);
p->data=val;
p->next=p;
return p;
}
//头插法
void Insert_Chead(CList plist,int val)
{
CNode *p=BuyCNode(val);
p->next=plist->next;
plist->next=p;
}
//尾插法,比较符合人类习惯
void Insert_Ctail(CList plist,int val)
{
CNode *p=BuyCNode(val);
CNode *p1;
for(p1=plist->next;p1!=plist;p1=p1->next)
{
if(p1->next==plist)
{
p1->next=p;
p->next=plist;
}
}
}
//打印
void ShowC(CList plist)
{
CNode *p;
for(p=plist->next;p!=plist;p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
//统计链表结点个数
int GetlengthC(CList plist)
{
CNode *p;
int i=0;
for(p=plist->next;p!=plist;p=p->next)
{
i++;
}
return i;
}
//查找与key值相同的第一个结点
CNode *Search(CList plist,int key)
{
CNode *p;
for(p=plist->next;p!=plist;p=p->next)
{
if(p->data==key)
{
printf("key=%d\n",p->data);
return p;
}
}
printf("未找到\n");
return NULL;
}
//删除与key相同的第一个元素
bool Delete(CList plist,int key)
{
CNode *p;
CNode *q;
for(p=plist->next;p!=plist;p=p->next)
{
if(p->data==key)
{
q->next=p->next;
free(p);
return true;
}
q=p;
}
return false;
}
//销毁
void Destroy(CList plist)
{
CNode *p;
CNode *q;
for(p=plist->next;p!=plist;p=p->next)
{
q=p;
free(q);
}
}
test.cpp
#include "clist.h"
int main()
{
CNode head;
InitCList(&head);
for(int i=0;i<10;i++)
{
Insert_Chead(&head,i);
}
//ShowC(&head);
Search(&head,8);
Search(&head,10);
printf("%d\n",Delete(&head,8));
printf("%d\n",Delete(&head,10));
ShowC(&head);
Destroy(&head);
}