首页 > 代码库 > 列表实现例子
列表实现例子
1 #ifndef LIST_H_ 2 #define LIST_H_ 3 4 #include <stdbool.h> 5 #define TSIZE 45 6 7 typedef struct film 8 { 9 char title[TSIZE];10 int rating;11 } Item;12 13 typedef struct node14 {15 Item item;16 struct node * next;17 } Node;18 19 typedef Node * List;20 21 void InitializeList(List * plist);22 23 bool ListIsEmpty(const List * plist);24 25 bool ListIsFull(const List * plist);26 27 unsigned int ListItemCount(const List * plist);28 29 bool AddItem(Item item, List * plist);30 31 void Traverse(const List * plist, void (* pfun)(Item item));32 33 void EmptyTheList(List * plist);34 35 #endif
#include <stdio.h>#include <stdlib.h>#include "list.h"void showmovie(Item item){ printf("Movie: %s, rating: %d\n", item.title, item.rating);}int main(void){ List movies; Item temp; InitializeList(&movies); if(ListIsFull(&movies)) { fprintf(stderr, "Memory allocating failed!\n"); exit(1); } printf("Enter first movie title: "); while(NULL != gets(temp.title) && ‘\0‘ != temp.title[0]) { printf("your rating: "); scanf("%d", &temp.rating); while(‘\n‘ != getchar()) continue; if(false == AddItem(temp, &movies)) { fprintf(stderr, "Add item error!\n"); break; } if(ListIsFull(&movies)) { printf("List is full!\n"); break; } printf("Enter next movie title: "); } if(ListIsEmpty(&movies)) printf("No data entered!\n"); else { printf("Here is the movies list:\n"); Traverse(&movies, showmovie); } printf("You have enter %d movies!\n", ListItemCount(&movies)); EmptyTheList(&movies); printf("Bye!\n"); return 0;}
#include <stdio.h>#include <malloc.h>#include "list.h"void CopyToNode(Item item, Node * pnode){ pnode->item = item;}void InitializeList(List * plist){ *plist = NULL;}bool ListIsEmpty(const List * plist){ if(NULL == *plist) return true; else return false;}bool ListIsFull(const List * plist){ Node * pn = (Node *)malloc(sizeof(Node)); bool full; if(NULL == pn) full = true; else full = false; free(pn); return full;}unsigned int ListItemCount(const List * plist){ unsigned int count = 0; Node * pn = *plist; while(NULL != pn) { count++; pn = pn->next; } return count;}bool AddItem(Item item, List * plist){ Node * pnew, * pdest = *plist; pnew = (Node *)malloc(sizeof(Node)); if(NULL == pnew) return false; CopyToNode(item, pnew); pnew->next = NULL; if(NULL == pdest) { *plist = pnew; } else { while(NULL != pdest->next) pdest = pdest->next; pdest->next = pnew; } return true;}void Traverse(const List * plist, void (* pfun)(Item item)){ Node * pn = *plist; while(NULL != pn) { (*pfun)(pn->item); pn = pn->next; }}void EmptyTheList(List * plist){ Node * pn; while(NULL != *plist) { pn = (*plist)->next; free(*plist); *plist = pn; }}
列表实现例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。