static关键字声明的全局变量只有本文件内的函数可以引用,其它文件(模块)只能通过该模块提供的接口函数来访问这个static全局变量,而不能直接对其进行操作。
对于一个存储类别声明为static的全局变量而言,其生命周期并没哟发生改变,在整个程序执行过程中该变量一直存在。但其作用域反而有所减小,只有本文件的函数可以引用该全局变量。
1 /*
2 * FILE: p65_linkOperate_list.c
3 * DATE: 20180107
4 * --------------
5 * DESCRIPTION: static全局变量只有本文件内的函数可以引用
6 * 其它文件(模块)只能通过该模块提供的接口函数来访问这个static全局变量
7 * insert插入节点,print遍历打印节点,destroy遍历释放节点
8 */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12
13 struct node{
14 int val;
15 struct node *next;
16 };
17
18 // static 链表头
19 static struct node *head;
20
21 /* 插入节点 */
22 int insert(int val)
23 {
24 struct node *p, *q;
25 p = head;
26 // 创建新节点
27 q = (struct node *)malloc(sizeof(struct node));
28 if(q == NULL)
29 {
30 perror("ERROR: malloc, fail to apply memory");
31 return -1;
32 }
33 q->val = val;
34 q->next = NULL;
35 // 节点链入链表
36 if(p == NULL)
37 {
38 head = q; // 注意 此处不是 p=q
39 }
40 else
41 {
42 while(p->next != NULL)
43 p = p->next;
44 p->next = q;
45 }
46 return 0;
47 }
48
49 /* 遍历链表,打印每个节点的值 */
50 void print()
51 {
52 struct node *p = head;
53 while(p != NULL)
54 {
55 printf("%d\n", p->val);
56 p = p->next;
57 }
58 }
59
60 /* 遍历链表,释放每一个节点 */
61 void destroy()
62 {
63 struct node *p = head;
64 while(p != NULL)
65 {
66 struct node *q;
67 q = p;
68 p = p->next;
69 free(q); // free 释放
70 }
71 head = NULL; // 清空链表的头指针
72 }
1 /* FILE: p65_linkOperate_list.h
2 * DATE: 20180107
3 * ---------------
4 */
5
6 extern int insert(int val);
7 extern void print();
8 extern void destroy();
1 /* FILE: p65_linkOperate_main.c
2 * DATE: 20180107
3 * --------------
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #include "p65_linkOperate_list.h"
10
11 int main(void)
12 {
13 int i;
14 for(i=0; i<5; i++)
15 {
16 if(insert(i) < 0)
17 exit(-1);
18 }
19 print();
20 destroy();
21 return 0;
22 }
1 # FILE: Makefile
2 # DATE: 20180107
3 # ==============
4
5 OBJECTS = p65_linkOperate_list.o p65_linkOperate_main.o
6
7 build: $(OBJECTS)
8 gcc -o build $(OBJECTS)
9
10 p65_linkOperate_list.o: p65_linkOperate_list.c
11 gcc -c p65_linkOperate_list.c
12
13 p65_linkOperate_main.o: p65_linkOperate_list.h p65_linkOperate_main.c
14 gcc -c p65_linkOperate_main.c
15
16 .PHONY: clean
17 clean:
18 rm build $(OBJECTS)
补充删除指定节点函数
49 /* 删除指定节点 */
50 int del(int val)
51 {
52 struct node *p, *q;
53 p = head;
54 if(p == NULL) // 链表为空
55 {
56 fprintf(stderr, "ERROR: the link-list is empty.\n");
57 return -1;
58 }
59 if(p->val == val) // 第一个节点就是要删除的节点
60 {
61 head = p->next;
62 free(p);
63 return 0;
64 }
65 else if(p->next == NULL) // 只有一个节点,且不是所要删除的
66 {
67 printf("ERROR: delete, nOt found\n");
68 return -1;
69 }
70 q = p;
71 p = p->next;
72 while(p != NULL)
73 {
74 if(p->val == val)
75 {
76 q->next = p->next;
77 free(p);
78 printf("SUCCESS: delete.\n");
79 return 0;
80 }
81 q = p;
82 p = p->next;
83 }
84 printf("ERROR: delete, nOt found\n");
85 return -1;
86 }