loop_list.c:
1 #include"loop_list.h"
2 //创建头结点
3 loop_p create_head()
4 {
5 loop_p L=(loop_p)malloc(sizeof(loop_list));
6 if(L==NULL)
7 {
8 printf("空间申请失败\n");
9 return NULL;
10 }
11 L->len=0;
12 L->next=L;
13 return L;
14 }
15 //创建新节点
16 loop_p create_node(datatype data)
17 {
18 loop_p new=(loop_p)malloc(sizeof(loop_list));
19 if(new==NULL)
20 {
21 printf("空间申请失败\n");
22 return NULL;
23 }
24 new->data=data;
25 new->next=NULL;
26 return new;
27 }
28 //头插
29 void insert_head(loop_p H,datatype data)
30 {
31 if(H==NULL)
32 {
33 printf("入参为空,请检查\n");
34 return;
35 }
36 loop_p new=create_node(data);
37 new->next=H->next;
38 H->next=new;
39 H->len++;
40 }
41 //判空
42 int loop_link_empty(loop_p H)
43 {
44 if(H==NULL)
45 {
46 printf("入参为空,请检查\n");
47 return -1;
48 }
49 return H->next==H?1:0;
50 }
51 //按位置插入
52 void insert_pos(loop_p H,datatype data,int pos)
53 {
54 if(H==NULL)
55 {
56 printf("入参为空,请检查\n");
57 return;
58 }
59 if(pos<=0||pos>H->len+1)
60 {
61 printf("位置不合理\n");
62 return;
63 }
64 loop_p p=H;
65 for(int i=0;i<pos-1;i++)
66 {
67 p=p->next;
68 }
69 loop_p new=create_node(data);
70 new->next=p->next;
71 p->next=new;
72 H->len++;
73 }
74 //输出
75 void output_loop(loop_p H)
76 {
77 if(H==NULL)
78 {
79 printf("入参为空,请检查\n");
80 return;
81 }
82 loop_p p=H->next;
83 while(p!=H)
84 {
85 printf("%d->",p->data);
86 p=p->next;
87 }
88 printf("%s","H");
89 putchar(10);
90 }
91 //尾删
92 void del_tail(loop_p H)
93 {
94 if(H==NULL)
95 {
96 printf("入参为空,请检查\n");
97 return;
98 }
99 if(loop_link_empty(H))
100 {
101 printf("链表为空,无需删除\n");
102 return;
103 }
104 loop_p p=H;
105 while(p->next->next!=H)
106 {
107 p=p->next;
108 }
109 loop_p del=p->next;
110 p->next=p->next->next;
111 free(del);
112 H->len--;
113 }
114 //按位置删除
115 void del_pos(loop_p H,int pos)
116 {
117 if(H==NULL)
118 {
119 printf("入参为空,请检查\n");
120 return;
121 }
122 if(loop_link_empty(H))
123 {
124 printf("链表为空,无需删除\n");
125 return;
126 }
127 if(pos<=0||pos>=H->len+1)
128 {
129 printf("位置不合理\n");
130 return;
131 }
132 loop_p p=H;
133 for(int i=0;i<pos-1;i++)
134 {
135 p=p->next;
136 }
137 loop_p del=p->next;
138 p->next=p->next->next;
139 free(del);
140 H->len--;
141 }
main.c:
#include"loop_list.h"
2 int main()
3 {
4 loop_p H=create_head();
5 insert_head(H,90);
6 insert_head(H,80);
7 insert_head(H,77);
8 del_pos(H,4);
9 output_loop(H);
10 return 0;
11 }
loop_list.h:
#ifndef __LOOP_LIST_H__
2 #define __LOOP_LIST_H__
3 #include<stdio.h>
4 #include<stdlib.h>
5 typedef int datatype;
6 typedef struct loop_list
7 {
8 union
9 {
10 int len;
11 datatype data;
12 };
13 struct loop_list *next;
14 }loop_list,*loop_p;
15 loop_p create_head();
16 loop_p create_node(datatype data);
17 void insert_head(loop_p H,datatype data);
18 int loop_link_empty(loop_p H);
19 void insert_pos(loop_p H,datatype data,int pos);
20 void output_loop(loop_p H);
21 void del_tail(loop_p H);
22 void del_pos(loop_p H,int pos);
23
24 #endif
2024/2/25
最新推荐文章于 2024-07-11 21:47:44 发布