// 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 #include #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; //结构赋值 }