一、dLoopLink.h
#ifndef __DLOOPLINK_H__
#define __DLOOPLINK_H__
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct node
{
union
{
int len;
DataType data;
};
struct node* next;
struct node* prior;
}dLoopLink, *dLoopLinkPtr;
//创建
dLoopLinkPtr create();
//判空
int empty(dLoopLinkPtr H);
//尾插
int tail_add(dLoopLinkPtr H, DataType e);
//遍历
void show(dLoopLinkPtr H);
//尾删
int tail_del(dLoopLinkPtr H);
//销毁
void my_free(dLoopLinkPtr H);
#endif
二、dLoopLink.c
#include "dLoopLink.h"
//创建
dLoopLinkPtr create()
{
dLoopLinkPtr H = (dLoopLinkPtr)malloc(sizeof(dLoopLink));
if(NULL == H)
{
printf("创建失败!\n");
return NULL;
}
H->len = 0;
H->next = NULL;
H->prior = NULL;
printf("创建成功!\n");
return H;
}
//判空
int empty(dLoopLinkPtr H)
{
if(NULL == H)
{
printf("判空失败!\n");
return -1;
}
return H->len==0;
}
//尾插
int tail_add(dLoopLinkPtr H, DataType e)
{
if(NULL == H || empty(H))
{
printf("插入失败!\n");
return 0;
}
dLoopLinkPtr p = (dLoopLinkPtr)malloc(sizeof(dLoopLink));
if(NULL == p)
{
printf("申请节点失败!\n");
return 0;
}
p->data = e;
p->next = NULL;
p->prior = NULL;
dLoopLinkPtr q = H;
for(int i=0; i<H->len; i++)
{
q = q->next;
}
p->next = H->next;
p->prior = q;
H->prior = p;
q->next = p;
H->len++;
return 1;
}
//遍历
void show(dLoopLinkPtr H)
{
if(NULL == H || empty(H))
{
printf("遍历失败!\n");
return ;
}
dLoopLinkPtr p = H;
while(H->next != H)
{
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
//尾删
int tail_del(dLoopLinkPtr H)
{
if(NULL == H || empty(H))
{
printf("删除失败!\n");
return 0;
}
dLoopLinkPtr p = H;
while(p->next != H)
{
p = p->next;
}
p->prior->next = H;
H->prior = p->next->prior;
free(p);
p=NULL;
return 1;
}
//销毁
void my_free(dLoopLinkPtr H)
{
if(NULL == H)
{
return ;
}
while(H->next != H)
{
tail_del(H);
}
free(H);
H=NULL;
printf("销毁成功!\n");
}
三、main.c
#include "dLoopLink.h"
int main()
{
dLoopLinkPtr H = create();
//尾插
tail_add(H, 10);
tail_add(H, 20);
tail_add(H, 30);
tail_add(H, 40);
tail_add(H, 50);
//遍历
show(H);
//尾删
tail_del(H);
show(H);
//销毁
my_free(H);
H=NULL;
return 0;
}