带头结点循环链表
程序员文章站
2022-03-15 19:25:45
...
上一个说的是单链表,其实循环链表跟单链表类似,单链表最后一个节点(p)的next域为NULL即p->next=NULL而循环链表(plist)的则为头结点的地址,即p->next=plist。其余的基本操作和单链表几乎一样,仅仅是单链表循环结束条件为!=NULL,而循环链表是!=plist。
基本操作为:初始化,插入(头插、尾插),查找,删除,判空,求长,摧毁,逆置。
.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)
{
CNode *p = (CNode *)malloc(sizeof(CNode));
assert(p != NULL);//
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;//q->next = plist;
p->next = q;
return true;
}
CNode *Search(CList plist,int key)//List
{
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 = Search(plist,key);
CNode *q;
if(p == NULL)
{
return false;
}
if(p->next != plist)//p不是最后的节点,删除p后面的点,将后面的数据赋值到p中
{
q = p->next;
p->next = q->next;
p->data = q->data;
free(q);
}
else//p是最后一个点
{
for(q=plist;q->next!=p;q=q->next) ;//找到p的前驱,然后删除p
q->next = p->next;
free(p);
}
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");
}
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);
}
}
void Revers(CList plist)
{
if(plist==NULL||plist->next==NULL||plist->next->next==NULL)
{
return;
}
CNode *p=plist->next;
CNode *q;
plist->next=plist;
while(p!=plist)
{
q=p->next;
p->next=plist->next;
plist->next=p;
p=q;
}
}
.h:
#pragma once
//循环链表,尾节点的next指向头节点
typedef struct CNode
{
int data;
struct CNode *next;
}CNode,*CList;
void InitList(CList plist);//Node *plist
//头插
bool Insert_Head(CList plist,int val);
//尾插
bool Insert_Tail(CList plist,int val);
CNode *Search(CList plist,int key);//List
bool Delete(CList plist,int key);
bool IsEmpty(CList plist);
int GetLength(CList plist);
void Show(CList plist);
void Clear(CList plist);
void Destroy(CList plist);
void Revers(CList plist);
上一篇: 文件读写和成绩排序