blob: e4c425b540df3e66f7bd50e01f39664dae6a1992 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
// list.c and list.h contain source code I edited from book "C Primer Plus"
// Chapter17 practice problem 2 which contain codes from its example codes, and
// the author of "C Primer Plus" does not have a license for list.c and list.h,
// so the author of "C Primer Plus" has the copyright on list.c and list.h, so
// list.c and list.h can be considered non-free close souce proprietary code.
//list.c--支持列表操作的函数
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
//局部函数原型
static void CopyToNode(Item item, Node * pnode);
//接口函数
//把列表设置为空列表
void InitializeList(List * plist)
{
plist->head=plist->end=NULL;
}
//如果列表为空则返回真
bool ListIsEmpty(const List * plist)
{
if(plist->head==NULL && plist->end==NULL)
return true;
else
return false;
}
//如果列表已满则返回真
bool ListIsFull(const List * plist)
{
Node * pt;
bool full;
pt=(Node *)malloc(sizeof(Node));
if(pt==NULL)
full=true;
else
full=false;
free(pt);
return full;
}
//返回节点数
unsigned int ListItemCount(const List * plist)
{
unsigned int count=0;
Node * pnode=plist->head; //设置到列表的开始处
while(pnode!=NULL)
{
++count;
pnode=pnode->next; //把1设置为下一个节点
}
return count;
}
//创建存放项目的节点,并把它添加到
//由plist指向的列表(较慢的实现方法?)尾部
bool AddItem(Item item, List * plist)
{
Node * pnew;
pnew=(Node *)malloc(sizeof(Node));
if(pnew==NULL)
return false; //(分配空间)失败时退出函数
CopyToNode(item, pnew);
pnew->next=NULL;
if(ListIsEmpty(plist)) //空列表,因此把pnew
{
plist->head=pnew; //放在列表头部
plist->end=pnew; //放在列表尾部
}
else
{
plist->end->next=pnew; //把pnew添加到结尾处
plist->end=pnew;
}
return true;
}
//访问每个节点并对它们分别执行有pfun指向的函数
void Traverse(const List * plist, void(* pfun)(Item item))
{
Node * pnode=plist->head;
while(pnode!=NULL)
{
(*pfun)(pnode->item);
pnode=pnode->next;
}
}
//释放由malloc()分配的内存
//把列表指针设置为NULL
void EmptyTheList(List * plist)
{
Node * psave;
while(plist->head != NULL)
{
psave=(plist->head)->next; //保存下一个节点的地址
free(plist->head); //释放当前节点
plist->head=psave; //前进到下一个节点
}
}
//局部函数定义
//把一个项目复制到一个节点中
static void CopyToNode(Item item, Node * pnode)
{
pnode->item=item; //结构赋值
}
|