单向循环链表
创建单向循环链表,创建节点 ,头插,按位置插入,输出,尾删,按位置删除功能
//main.c
#include "loop_list.h"
int main()
{loop_p H=create_head();insert_head(H,12);insert_head(H,6);insert_head(H,90);insert_head(H,123);out_put_loop(H);insert_pos(H,100,3);out_put_loop(H);del_tail(H);out_put_loop(H);del_pos(H,2);out_put_loop(H);return 0;
}
//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;}//判空
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 new = create_node(data);new->next = H->next;H->next = new;H->len++;
}
//按位置插入
void insert_pos(loop_p H,datatype data,int pos)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(pos>H->len+1||pos<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 out_put_loop(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","HEAD");putchar(10);
}
//尾删
void del_tail(loop_p H)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(loop_empty(H)){printf("链表为空,无需删除\n");return;}loop_p p = H;for(int i=0;i<p->len-1;i++){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>H->len||pos<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 insert_head(loop_p H,datatype data);//按位置插入
void insert_pos(loop_p H,datatype data,int pos);
//输出
void out_put_loop(loop_p H);//尾删
void del_tail(loop_p H);
//按位置删除
void del_pos(loop_p H,int pos);#endif
链表逆置函数
//单链表的逆置
void overturn_link(link_p H)
{if(H==NULL){printf("入参为空,请检查\n");return;}if(link_empty(H)){printf("链表为空\n");return;}if(H->next->next==NULL){printf("表中只有一个元素,无需翻转\n");return;}link_p p = H->next->next;H->next->next = NULL;link_p q = p->next;while(p!=NULL){p->next = H->next;H->next = p;p = q;if(q!=NULL){q = q->next;}}
}
//单链表的逆置
void overturn_link(link_p H)
{link_p p = H->next;link_p q = H;H->next = NULL;while(p){q=p;p = p->next;q->next = H->next;H->next = q;}
}
思维导图