头文件list.h
#include<stdbool.h> #ifndef LIST_H_ #define LIST_H_ #define T_SIZE 41 struct film{ char name[T_SIZE]; int ratting; }; typedef struct film Item; struct node{ Item data; struct node * next; }; typedef struct node Node; typedef Node * List; void initList(List * plist); bool listIsEmpty(const List * plist); bool listIsFull(const List * plist); unsigned int listItemCount(const List * plist); bool addItem(Item item, List * plist); //void traverse(const List * plist, void (*pfun)(Item item)); bool emptyTheList(List * plist); #endif
list的实现 list.c文件
#include<stdio.h> #include<stdlib.h> #include "list.h" void initList(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){ unsigned int count = 0; Node * temp; temp = *plist; while(temp != NULL){ count ++; temp = temp -> next; } return count; } bool addItem(Item item, List * plist){ bool result = false; Node *temp; Node *f; temp = (Node *)malloc(sizeof(Node)); if(temp == NULL){ free(temp); return false; } temp -> data = item; temp -> next = NULL; if(*plist == NULL) *plist = temp; else{ f = *plist; while(f -> next != NULL) f = f -> next; f -> next = temp; } f = NULL; temp = NULL; return true; } bool emptyTheList(List * plist){ Node *f; Node *p; p = *plist; f = p -> next; free(p); while(f != NULL){ p = f; f = f -> next; free(p); } p = NULL; f = NULL; *plist = NULL; return true; }
main.c文件:
#include<stdio.h> #include<string.h> #include"list.h" #define COUNT 10 int main(void){ List l; Item item; unsigned int count = 0; int i; initList(&l); strcpy(item.name, "su7"); item.ratting = 8; for(i = 0; i < COUNT; i++) addItem(item, &l); count = listItemCount(&l); printf("count is %u.\n", count); return 0; }
时间: 2024-10-16 15:34:57