aboutsummaryrefslogtreecommitdiff
path: root/list.c
diff options
context:
space:
mode:
Diffstat (limited to 'list.c')
-rw-r--r--list.c111
1 files changed, 111 insertions, 0 deletions
diff --git a/list.c b/list.c
new file mode 100644
index 0000000..49aeaac
--- /dev/null
+++ b/list.c
@@ -0,0 +1,111 @@
+// "C Primer Plus" Chapter17 practice 17 practice problem 2
+
+//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; //结构赋值
+}
+