实现创建单向循环链表、创建结点、判空、输出、头插、按位置插入、尾删、按位置删除
loop_list.c
#include "loop_list.h"
loop_p create_head()
{loop_p L=(loop_p)malloc(sizeof(loop_list));if(L==NULL){printf("空间申请失败\n");return NULL;}L->len=0;L->next=L;return L;
}
loop_p create_node(datatype data)
{loop_p new=(loop_p)malloc(sizeof(loop_list));if(new==NULL){printf("空间申请失败\n");return NULL;}new->data=data;return new;
}
void out_put_loop(loop_p H)
{if(H==NULL){printf("入参为空,请检查\n");return;}loop_p p=H->next;while(p!=H){printf("%d->",p->data);p=p->next;}printf("%s","H");putchar(10);
}int loop_empty(loop_p H)
{if(H==NULL){printf("入参为空,请检查\n");return -1;}return H->next==H?1:0;
}
void insert_head(loop_p H,datatype data)
{if(H==NULL){printf("入参为空,请检查\n");return;}loop_p p=H;loop_p new=create_node(data);new->next=p->next;p->next=new;H->len++;
}
void insert_pos(loop_p H,datatype data,int pos)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(pos<=0||pos>H->len+1){printf("位置不合理\n");return;}loop_p p = H;for(int i = 0;i<pos-1;i++){p = p->next;}loop_p new = create_node(data);new->next = p->next;p->next = new;H->len++;
}
void del_tail(loop_p H)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(loop_empty(H)){printf("链表为空\n");return;}loop_p p = H;while(p->next->next!=H){p = p->next;}loop_p del = p->next; p->next = p->next->next;free(del);H->len--;
}
void del_pos(loop_p H,int pos)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(loop_empty(H)){printf("链表为空\n");return;}if(pos<=0||pos>H->len+1){printf("位置不合理\n");return;}loop_p p=H;for(int i=0;i<pos-1;i++){p=p->next;}loop_p del=p->next;p->next=p->next->next;free(del);H->len--;}
loop_list.h
#ifndef __LOOP_LIST_H__
#define __LOOP_LIST_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct loop_list
{union{int len;datatype data;};struct loop_list *next;
}loop_list,*loop_p;//创建单向循环链表
loop_p create_head();
//创建结点
loop_p create_node(datatype data);
//判空
int loop_empty(loop_p H);
//输出
void out_put_loop(loop_p H);
//头插
void insert_head(loop_p H,datatype data);
//按位置插入
void insert_pos(loop_p H,datatype data,int pos);
//尾删
void del_tail(loop_p H);
//按位置删除
void del_pos(loop_p H,int pos);#endif
mian.c
#include "loop_list.h"
int main()
{loop_p H = create_head();insert_head(H,4);insert_head(H,3);insert_head(H,2);insert_head(H,1);out_put_loop(H);insert_pos(H,5,5);out_put_loop(H);del_tail(H);out_put_loop(H);del_pos(H,4);out_put_loop(H);return 0;
}
运行结果