1.h头文件
#ifndef __1_H_
#define __1_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 cha_head(loop_p H,datatype data);
void cha_tail(loop_p H,datatype data);
void out_put(loop_p H) ;
void cha_pos(loop_p H,datatype data,int pos) ;
void shan_pos(loop_p H,int pos);
#endif
1.c
#include"1.h"
loop_p create_head()
{loop_p L=(loop_p)malloc(sizeof(loop_list));if(L==NULL){printf("申请失败");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("申请失败");return NULL;}new->data=data;return new;
}
//判空
int loop_empty(loop_p H)
{if(H==NULL){printf("入参为空");return 1;}return H->next==NULL?1:0;
}
//头
void cha_head(loop_p H,datatype data)
{ if(H==NULL){printf("入参为空,请检查\n");return;}loop_p new=create_node(data);new->next=H->next;H->next=new;H->len++;
}
//尾插
void cha_tail(loop_p H,datatype data)
{if(H==NULL){printf("入参为空,请检查\n");return;}loop_p p=H;while(p->next !=H){p=p->next;}loop_p new=create_node(data);new->next=p->next;p->next=new;H->len++;
}
//输出
void out_put(loop_p H)
{if(H==NULL){printf("入参为空,请检查\n");return;}//定义一个新的结点循环整条链表loop_p p = H->next; //H不属于链表中的元素//最后一个结点进入循环while(p!=H){printf("%d->",p->data);p = p->next;}printf("%s","NULL");putchar(10);
}
//按位置插入
void cha_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 shan_pos(loop_p H,int pos)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(loop_empty(H)){printf("链表为空\n");return;}//pos合理性判断if(pos<=0||pos>H->len){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=del->next;free(del);H->len--;
}
main.c
#include "1.h"
int main()
{loop_p H=create_head();
// create_node();cha_head(H,30);cha_head(H,40);cha_head(H,50);cha_tail(H,99);out_put(H);shan_pos(H,2);out_put(H);cha_pos(H,55,3);out_put(H);}