失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 抽象数据类型(ADT) 双链表实现

抽象数据类型(ADT) 双链表实现

时间:2020-02-02 13:12:41

相关推荐

抽象数据类型(ADT) 双链表实现

/*main.c----测试函数*/#include<stdio.h>#include<stdlib.h>#include"list.h"static void show(const ITEM * item){printf("Film's name:%-20sRating:%-2d\n",item->title,item->rating);}int main(void){LIST plist;char input[TSIZE];int rating;ITEM eitem;InitializeList(&plist);puts("Enter first movie title:");while(gets(input)!=NULL && input[0] != '\0'){strcpy(eitem.title,input);puts("Enter your rating<0-10>:");scanf("%d",&(eitem.rating));while(getchar() != '\n') continue;AddItem(&eitem,&plist);puts("Enter next movie title(empty line to stop):");}Traverse(&plist,show,0);putchar('\n');Traverse(&plist,show,1);system("pause");return 0;}

/*list.c----定义接口*/#ifndef LIST_H_INCLUDED#define LIST_H_INCLUDED#include<stdio.h>#include<stdbool.h>#define TSIZE 45#define ITEMSIZE 10struct film{char title[TSIZE];int rating;};typedef struct film ITEM;typedef struct node{ ITEM item;struct node *next;struct node *previous;}NODE;typedef struct list{ NODE *head; NODE *end;int count;}LIST;void InitializeList(LIST *plist);bool ListIsEmpty(const LIST *plist);bool ListIsFull(const LIST * plist);int ListItemCount(const LIST * plist);bool AddItem(ITEM *item,LIST * plist);void Traverse(const LIST * plist,void (*pfun)(const ITEM * item),int direction);#endif // LIST_H_INCLUDED

/*list.c实现接口*/#include"list.h"#include<stdio.h>static void CopyToNode(NODE *pnode,ITEM *pitem);void InitializeList(LIST *plist){plist->head = NULL;plist->end = NULL;plist->count = 0;}bool ListIsEmpty(const LIST *plist){if(plist->count == 0)return true;elsereturn false;}bool ListIsFull(const LIST * plist){if(plist->count == ITEMSIZE)return true;elsereturn false;}int ListItemCount(const LIST * plist){return plist->count;}bool AddItem(ITEM *item,LIST * plist){NODE *pnode;if(ListIsFull(plist)){printf("List full!\n");return false;}pnode = (NODE*)malloc(sizeof(NODE));if(pnode == NULL){printf("Disk full!\n");return false;}elseCopyToNode(pnode,item);if(plist->head == NULL)plist->head = pnode;else{plist->end->next = pnode;pnode->previous = plist->end;}plist->end = pnode;plist->count++;}void Traverse(const LIST * plist,void (*pfun)(const ITEM * item),int direction){int i;LIST current = *plist;if(ListIsEmpty(plist)){printf("List is empty!\n");return;}if(direction == 0){while(current.head != NULL){(*pfun)(&(current.head->item));current.head = current.head->next;}}else{while(current.end != NULL){(*pfun)(&(current.end->item));current.end = current.end->previous;}}printf("Here are %d movie.\n",ListItemCount(plist));}static void CopyToNode(NODE *pnode,ITEM *pitem){pnode->item = *pitem;pnode->next = NULL;pnode->previous = NULL;}

如果觉得《抽象数据类型(ADT) 双链表实现》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。