假设list.h如下定义列表:
typedef struct list { Node * head; /* 指向列表首 */ Node * end; /* 指向列表尾 */ } List;
根据这个定义,重写list.c函数,并用films3.c测试结果代码。
/* list.c -- 支持列表操作 */ #include <stdio.h> #include <stdlib.h> #include "lish.h" /* 局部函数原型 */ static void CopyToNode(Item item, Node * pnode); /* 接口函数 */ /* 把列表设置为空列表 */ void InitializeList (List * plist) { * plist = NULL; } /* 如果列表为空则返回真 */ bool ListIsEmpty(const List * plist) { if (* plist == 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) { unsigened int count = 0; Node * pnode = *plist; /*设置到列表的开始处 */ while (pnode != NULL) { ++count; pnode = pnode ->next; /* 把1设置为下一个节点 */ } return count; } /* 创建存放项目的节点,并把它添加到 */ /* 由plist指向的列表(较慢的实现方法)尾部*/ bool AddItem(Item item, List * plist) { Node * pnew; Node * scan = *plist; pnew = (Node *)malloc(sizeof (Node)); if (pnew == NULL) return false; /* 失败时退出函数 */ CopyToNode (item, pnew); pnew->next = NULL; if (scan == NULL) /* 空列表,因此把pnew */ * plist = pnew; /* 放在列表头部 */ else { while (scan->next != NULL) scan = scan->next; /* 找到列表结尾 */ scan->next = pnew; /* 把pnew添加到结尾处 */ } return true; } /* 访问每个节点并对它们分别执行由pfun指向的函数 */ void Traverse (const List * plist, void (* pfun)(Item item)) { Node * pnew = *plist; /* 设置到列表的开始处 */ while (pnode!= NULL) { (* pfun)(pnode->item); /* 把函数作用于列表中的项目 */ pnode = pnode ->next; /* 前进到下一项 */ } } /* 释放由malloc()分配的内存 */ /* 把列表指针设置为NULL */ void EmptyTheList(List * plist)' { Node * psave; while (*plist != NULL) { psave = (*plist) ->next; /* 保存下一个节点的地址 */ free (*plist); /* 释放当前节点 */ *plist = psave; /* 前进到下一个节点 */ } } /* 局部函数定义 */ /* 把一个项目复制到一个节点中 */ static void CopyToNode(Item item, Node * pnode) { pnode->item = item; /* 结构复制 */ }
/* films3.c -- 使用ADT风格的链表 */ /* 和list.c一同编译 */ #include <stdio.h> #include <stdlib.h> /* 为exit()提供原型 */ #include "list.h" /* 定义List,Item */ void showmovies (Item item); int main(void) { List movies; Item temp; /* 初始化 */ InitializeList(&movies); if (ListIsFull (movies)) { fprintf(stderr, "No memory available! Bye!\n"); exit(1); } /* 收集并存储 */ puts("Enter your rating <0-10>: "); scanf("%d", &temp.rating); while(getchar () != '\n') continue; if (AddItem(temp, &movies) ==false) { fprintf(stderr, "Problem allocating memory\n"); break; } if (ListIsFull (movies)) { puts("The list is now full."); break; } puts("Enter next movies title (empty line to stop): "); } /* 显示 */ if (ListIsEmpty (movies)) printf("No data entered. "); else { printf ("Here is the movies list: \n"); Traverse(movies, showmovies); } printf("You entered %d movies.\n", ListItemCount (movies)); /* 清除 */ EmptyTheList(&movies); printf("Bye!\n"); return 0; } void showmovies(Item item) { printf("Movie: %s Rating: %d\n", item.title, item.rating); }