一、loopLink.h
#ifndef __LOOPLINK_H__
#define __LOOPLINK_H__#include <stdio.h>
#include <stdlib.h>typedef int DataType;typedef struct node
{union{int len;DataType data;};struct node* next;
}loopLink, *loopLinkPtr;//创建
loopLinkPtr create();//判空
int empty(loopLinkPtr H);//尾插
int tail_add(loopLinkPtr H, DataType e);//遍历
void show(loopLinkPtr H);//尾删
int tail_del(loopLinkPtr H);//销毁
void my_free(loopLinkPtr H);#endif
二、loopLink.c
#include "loopLink.h"//创建
loopLinkPtr create()
{loopLinkPtr H = (loopLinkPtr)malloc(sizeof(loopLink));if(NULL == H){printf("创建失败!\n");return NULL;}H->len = 0;H->next = H;printf("创建成功!\n");return H;
}//判空
int empty(loopLinkPtr H)
{if(NULL == H){printf("判空失败!\n");return -1;}return H->len==0;
}//尾插
int tail_add(loopLinkPtr H, DataType e)
{if(NULL == H){printf("尾插失败!\n");return 0;}loopLinkPtr p = (loopLinkPtr)malloc(sizeof(loopLink));if(NULL == p){printf("申请节点失败!\n");return 0;}p->data = e;p->next = NULL;loopLinkPtr q = H;while(q->next != H){q = q->next;}q->next = p;p->next = H;H->len++;return 1;
}//遍历
void show(loopLinkPtr H)
{if(NULL == H || empty(H)){printf("遍历失败!\n");return ;}loopLinkPtr p = H;for(int i=0; i<H->len; i++){p = p->next;printf("%d ", p->data);}printf("\n");
}//尾删
int tail_del(loopLinkPtr H)
{if(NULL == H || empty(H)){printf("删除失败!\n");return 0;}loopLinkPtr q = H;for(int i=0; i<H->len-1; i++){q = q->next;}free(q->next);q->next = H;H->len--;return 1;
}//销毁
void my_free(loopLinkPtr H)
{if(NULL == H){printf("销毁失败!\n");return ;}while(H->next != H){tail_del(H);}free(H);H=NULL;printf("销毁成功!\n");
}
三、main.c
#include "loopLink.h"int main()
{loopLinkPtr 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;
}
四、执行结果
五、知识点思维导图