loopdouble.h
#ifndef __LOOPDOUBLE_H__
#define __LOOPDOUBLE_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
union
{
int len;
datatype data;
};
struct node *next;
struct node *prior;
}loopdouble,*loopdoubleptr;
//创建双向循环链表
loopdoubleptr create();
//判空
int empty(loopdoubleptr H);
//尾插
void tail_add(loopdoubleptr H,datatype e);
//输出
void show(loopdoubleptr H);
//尾删
void tail_del(loopdoubleptr H);
//销毁
void free_ld(loopdoubleptr H);
#endif
loopdouble.c
#include "loopdouble.h"
//创建双向循环链表
loopdoubleptr create()
{
loopdoubleptr H=(loopdoubleptr)malloc(sizeof(loopdouble));
if(H==NULL)
{
printf("创建失败");
return NULL;
}
H->len=0;
H->next=H;
H->prior=H;
printf("创建成功\n");
return H;
}
//判空
int empty(loopdoubleptr H)
{
if(H==NULL)
{
printf("判空失败\n");
return -1;
}
return H->len==0;
}
//尾插
void tail_add(loopdoubleptr H,datatype e)
{
if(H==NULL)
{
printf("尾插失败\n");
return;
}
loopdoubleptr p=(loopdoubleptr)malloc(sizeof(loopdouble));
if(p==NULL)
{
printf("申请失败\n");
return;
}
p->data=e;
p->next=NULL;
p->prior=NULL;
loopdoubleptr q=H;
while(q->next!=H)
q=q->next;
p->next=H;
p->prior=q;
q->next=p;
H->prior=p;
H->len++;
}
//输出
void show(loopdoubleptr H)
{
if(H==NULL||empty(H))
{
printf("输出失败\n");
return;
}
loopdoubleptr p=H;
while(p->next!=H)
{
p=p->next;
printf("%d ",p->data);
}
printf("\n");
}
//尾删
void tail_del(loopdoubleptr H)
{
if(H==NULL||empty(H))
{
printf("尾删失败\n");
return;
}
loopdoubleptr q=H;
for(int i=0;i<H->len-1;i++)
q=q->next;
free(q->next);
q->next=H;
H->prior=q;
H->len--;
}
//销毁
void free_ld(loopdoubleptr H)
{
if(H==NULL)
{
printf("销毁失败\n");
return;
}
while(H->next!=H)
tail_del(H);
free(H);
H=NULL;
printf("销毁成功\n");
}
main.c
#include "loopdouble.h"
int main()
{
loopdoubleptr H=create();
tail_add(H,1);
tail_add(H,2);
tail_add(H,3);
show(H);
tail_del(H);
show(H);
free_ld(H);
}