1 /*---------------------------------------------
2 list.c -- 简单链表接口实现
3 ---------------------------------------------*/
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "list.h"
8
9 //把一项拷贝到节点中;CopyToNode 是辅助函数,不是接口函数
10 static void CopyToNode(Item item, Node *pnode)
11 {
12 pnode->item = item; //拷贝结构
13 }
14
15
16 //接口函数
17
18 void InitializeList(List *plist)
19 {
20 plist->head = NULL;
21 plist->size = 0;
22 }
23
24 bool ListIsEmpty(const List *plist)
25 {
26 if (plist->head == NULL)
27 return true;
28 else
29 return false;
30 }
31
32 bool ListIsFull(const List *plist)
33 {
34 bool full;
35 Node *pnode = (Node*)malloc(sizeof(Node));
36
37 if (pnode == NULL) //查看对内存是否已满,判断链表状态
38 full = true;
39 else
40 {
41 full = false;
42 free(pnode);
43 }
44
45 return full;
46 }
47
48 unsigned int ListItemCount(const List *plist)
49 {
50 return plist->size;
51 }
52
53 bool AddItem(Item item, List *plist)
54 {
55 Node *pnew = (Node*)malloc(sizeof(Node));
56 if (pnew == NULL) return false;
57
58 CopyToNode(item, pnew);
59 pnew->next = NULL;
60
61 Node *pscan = plist->head;
62
63 if (pscan == NULL)
64 plist->head = pscan = pnew;
65 else
66 {
67 while (pscan->next != NULL)
68 pscan = pscan->next;
69
70 pscan->next = pnew;
71 }
72
73 ++(plist->size);
74 return true;
75 }
76
77 void Tranverse(const List *plist, PFUN pfun)
78 {
79 Node *pnode = plist->head; //指针的拷贝,不改变 plist->head 的值
80 while (pnode != NULL)
81 {
82 (*pfun)(pnode->item);
83 pnode = pnode->next;
84 }
85 }
86
87 void EmptyTheList(List *plist)
88 {
89 Node *ptmp;
90 Node *pscan = plist->head;
91
92 while (pscan != NULL)
93 {
94 ptmp = pscan->next;
95 free(pscan);
96 pscan = ptmp;
97 }
98
99 plist->head = NULL; //销毁内存,头指针置为NULL
100 plist->size = 0; //销毁内存,节点数置为0
101 }