1、looplink.h
#ifndef __LOOPLINK_H__
#define __LOOPLINK_H__
typedef int datatype;
typedef struct Node
{
union{
datatype data;
int len;
};
struct Node *next;
}Looplink;
//创建
Looplink *list_create();
//判空
int list_empty(Looplink *L);
//尾插
int list_insert_tail(Looplink *L,datatype e);
//带头结点遍历
void list_show(Looplink *L);
//尾删
int list_delete_tail(Looplink *L);
//删头
Looplink *kill_head(Looplink *L);
//删除头结点后的遍历
void list_show2(Looplink *S);
#endif
2、looplink.c
#include<stdio.h>
#include<stdlib.h>
#include"looplink.h"
//创建
Looplink *list_create()
{
Looplink *L = (Looplink *)malloc(sizeof(Looplink));
if(L == NULL)
{
printf("创建失败\n");
return NULL;
}
L->len = 0;
L->next = L; //初始化时,头结点的指针域指向自己
printf("创建成功\n");
return L;
}
//判空
int list_empty(Looplink *L)
{
return L->next == L?1:0; //1表示空,0表示非空
}
//尾插
int list_insert_tail(Looplink *L,datatype e)
{
//判断逻辑
if(L ==NULL)
{
printf("所给链表不合法\n");
return -1;
}
//申请节点存放数据
Looplink *p = (Looplink *)malloc(sizeof(Looplink));
if(NULL == p)
{
printf("节点申请失败\n");
return -2;
}
p->data=e;
p->next=NULL;
Looplink *q = L;
while(q->next != L)
{
q=q->next;
}
p->next = L;
q->next = p;
L->len++;
printf("插入成功\n");
return 0;
}
//带头结点遍历
void list_show(Looplink *L)
{
if(L == NULL || list_empty(L))
{
printf("遍历失败\n");
return;
}
//遍历
printf("链表元素分别是:");
Looplink *q = L->next;
while(q != L)
{
printf("%d\t",q->data);
q=q->next;
}
putchar(10);
}
//尾删
int list_delete_tail(Looplink *L)
{
if(L == NULL || list_empty(L))
{
printf("尾删失败\n");
return -1;
}
Looplink *q = L;
while(q->next->next != L)
{
q=q->next;
}
free(q->next);
q->next=L;
L->len--;
printf("尾删成功\n");
return 0;
}
//删头
Looplink *kill_head(Looplink *L)
{
if(L ==NULL || list_empty(L))
{
printf("删头失败\n");
return NULL;
}
//遍历指针到最后一个
Looplink *q = L->next;
while(q->next != L)
{
q=q->next;
}
//孤立头结点
q->next = L->next;
//删除头结点
free(L);
L=NULL;
printf("头结点删除成功\n");
//返回第一个节点地址
return q->next;
}
//删除头结点后的遍历
void list_show2(Looplink *S)
{
if(S ==NULL)
{
printf("遍历失败\n");
return;
}
printf("链表元素分别是:");
Looplink *q = S;
do
{
printf("%d\t",q->data);
q=q->next;
}while(q != S);
putchar(10);
}
3、main.c
#include<stdio.h>
#include<stdlib.h>
#include"looplink.h"
int main(int argc, const char *argv[])
{
Looplink *L = list_create();
if(L == NULL)
{
return -1;
}
//尾插
list_insert_tail(L,8);
list_insert_tail(L,7);
list_insert_tail(L,6);
list_insert_tail(L,5);
list_insert_tail(L,4);
list_show(L);
//尾删
list_delete_tail(L);
list_show(L);
//删头
Looplink *S = kill_head(L);
L=NULL;
//删除头结点后遍历
list_show2(S);
return 0;
}
执行结果: