1.头文件
#ifndef __loop__
#define __loop__
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
union
{
datatype data;
int len;
};
struct node* next;
struct node* pri;
}node,*node_p;
//创建双向循环链表
node_p create_loop();
//创建节点
node_p create_node(datatype a);
//判空
int empty(node_p Q);
//尾插
int add_tail(node_p Q,datatype a);
//尾删
int dele_tail(node_p Q);
//输出
int show(node_p Q);
//销毁
void release(node_p *Q);
#endif
2.功能函数
#include "loop.h"
//创建双向循环链表
node_p create_loop()
{
node_p H=(node_p)malloc(sizeof(node));
if(H==NULL)
{
printf("堆区空间申请失败\n");
return NULL;
}
H->next=H;
H->pri=H;
H->len=0;
printf("双向循环链表创建成功\n");
return H;
}
//创建节点
node_p create_node(datatype a)
{
node_p new=(node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("节点空间申请失败\n");
return NULL;
}
new->next=NULL;
new->pri=NULL;
new->data=a;
return new;
}
//判空
int empty(node_p Q)
{
if(Q==NULL)
{
printf("参数传入失败\n");
return -1;
}
if(Q->len==0)
{
printf("链表为空\n");
return 1;
}
else
{
return 0;
}
}
//尾插
int add_tail(node_p Q,datatype a)
{
if(Q==NULL)
{
printf("参数传入失败\n");
return -1;
}
node_p H=create_node(a);
node_p p=Q;
for(int i=0;i<Q->len;i++)
{
p=p->next;
}
p->next->pri=H;
H->next=p->next;
H->pri=p;
p->next=H;
Q->len++;
return 1;
}
//尾删
int dele_tail(node_p Q)
{
if(Q==NULL)
{
printf("参数传入失败\n");
return -1;
}
if(empty(Q))
{
return 0;
}
node_p p=Q;
for(int i=0;i<Q->len;i++)
{
p=p->next;
}
p->next->pri=p->pri;
p->pri->next=p->next;
free(p);
Q->len--;
return 1;
}
//输出
int show(node_p Q)
{
if(Q==NULL)
{
printf("参数传入失败\n");
return -1;
}
if(empty(Q))
{
return 0;
}
node_p p=Q;
for(int i=0;i<Q->len;i++)
{
p=p->next;
printf("%d\t",p->data);
}
putchar(10);
return 1;
}
//释放
void release(node_p *Q)
{
if((*Q)==NULL)
{
printf("参数传入失败\n");
return ;
}
int k=(*Q)->len;
node_p p=(*Q);
for(int i=0;i<k;i++)
{
node_p temp=p;
p=p->next;
free(temp);
}
free(p);
*Q=NULL;
printf("链表已释放\n");
return;
}
3.主函数
#include "loop.h"
int main()
{
node_p H=create_loop();
add_tail(H,12);
add_tail(H,13);
add_tail(H,14);
add_tail(H,15);
show(H);
dele_tail(H);
dele_tail(H);
add_tail(H,21);
show(H);
release(&H);
return 1;
}
实现效果