1 #include<stdio.h>
2 #include<string.h>
3 #include<unistd.h>
4 #include<stdlib.h>
5 typedef int datatype;
6 typedef struct link_list
7 {
8 union
9 {
10 int len;
11 datatype data; //数据域
12 };
13 struct link_list *next; //指针域
14 }link_list,*link_p;
15 //实际在创建头结点,因为头结点指向整条链表
16 link_p create_head()
17 {
18 link_p L = (link_p)malloc(sizeof(link_list));
19 if(L==NULL)
20 {
21 printf("空间申请失败\n");
22 return NULL;
23 }
24 L->len=0; //创建时链表中没有元素,长度为0
25 L->next=NULL; //创建空的单链表,头结点没有指向,置空
26 return L;
27 }
28 //创建结点
29 link_p create_node(datatype data)
30 {
31 //在堆区申请一个结点的空间
32 link_p new = (link_p)malloc(sizeof(link_list));
33 if(new==NULL)
34 {
35 printf("空间申请失败\n");
36 return NULL;
37 }
38 new->data = data; //数据域赋值
39 return new; //返回申请的结点的首地址
40 }
41 //判空
42 int link_empty(link_p H)
43 {
44 if(H==NULL)
45 {
46 printf("入参为空,请检查\n");
47 return -1;
48 }
49 //如果头结点指向空说明链表为空
50 return H->next==NULL?1:0;
51 }
52 //头插
53 void insert_head(link_p H,datatype data)
54 {
55 //1\容错判断
56 if(H==NULL)
57 {
58 printf("入参为空,请检查\n");
59 return;
60 }
61 //申请新的结点
62 link_p new = create_node(data);
63 //新结点指向头结点的下一个结点
64 new->next = H->next;
65 //头结点指向新的结点
66 H->next = new;
67 H->len++;
68 }
69 //尾删
70 void del_tail(link_p H)
71 {
72 if(H==NULL)
73 {
74 printf("入参为空,请检查\n");
75 return;
76 }
77 if(link_empty(H))
78 {
79 printf("链表为空\n");
80 return;
81 }
82 //找到倒数第二个结点
83 link_p p = H;
84
85 //倒数第二个结点的特征:p->next->next = NULL
86 while(p->next->next!=NULL)
87 {
88 p = p->next;
89 }
90 link_p del = p->next;
91 //保存要删除的结点
92 //让倒数第二个结点的指针域置空
93 p->next = p->next->next;
94 free(del);
95 H->len--;
96 }
97 void out_put(link_p H)
98 {
99 if(H==NULL)
100 {
101 printf("入参为空,请检查\n");
102 return;
103 }
104 link_p p = H->next;
105 while(p!=NULL)
106 {
107 printf("%d->",p->data);
108 p = p->next;
109 }
110 printf("%s","NULL");
111 putchar(10);
112 }
113
114 int main(int argc, char *argv[])
115 {
116 link_p H=create_head();
117 insert_head(H,90);
118 insert_head(H,70);
119 insert_head(H,66);
120 out_put(H);
121 FILE* fp=fopen("text1","w");
122 while(H->next!=NULL)
123 {
124 fprintf(fp,"%d ",H->next->data);
125 H = H->next;
126 }
127 fprintf(fp,"\n");
128 fclose(fp);
129 int data=0;
130 fp=fopen("text1","r");
131 link_p P=create_head();
132 while(1)
133 {
134 int a=fscanf(fp,"%d",&data);
135 if(a!=1)
136 {
137 break;
138 }
139 else
140 {
141 insert_head(P,data);
142 }
143 }
144 fclose(fp);
145 out_put(P);
146 return 0;
147 }
2024/2/29
最新推荐文章于 2024-10-16 22:52:46 发布