《算法导论》第10章 基本数据结构 (2)链表
《算法导论》里实现的是无序双向链表。
源文件 list.h:链表的接口,定义链表和结点的类型,以及链表支持的操作。
typedef int DATA_TYPE; // 注意将结构声明为新类型的语法 struct tagNode { DATA_TYPE data; struct tagNode *prev, *next; }; typedef struct tagNode Node; typedef struct { Node *head; } List; List * list_create(void); Node * node_create(DATA_TYPE k); void list_destory(List*); void list_print(List*); Node * list_search(List*, DATA_TYPE); void list_insert(List*, Node*); void list_delete(List*, Node*);
源文件 list.c:链表的实现。
#include <stdio.h> #include <stdlib.h> #include "list.h" List * list_create(void) { return malloc(sizeof(List)); } Node * node_create(DATA_TYPE k) { Node *node = malloc(sizeof(Node)); node->data = k; node->prev = NULL; node->next = NULL; return node; } void list_destory(List *list) { free(list); } void list_print(List* list) { Node *node = list->head; while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("\n"); } Node * list_search(List *list, DATA_TYPE k) { Node *node = list->head; while (node != NULL && node->data != k) node = node->next; return node; } void list_insert(List *list, Node *x) { x->next = list->head; if (list->head != NULL) list->head->prev = x; list->head = x; x->prev = NULL; } void list_delete(List *list, Node *x) { if (x->prev != NULL) x->prev->next = x->next; else list->head = x->next; if (x->next != NULL) x->next->prev = x->prev; }
源文件 list_test.c:测试数据。
#include <stdio.h> #include "list.h" int main(void) { List *list = list_create(); list_insert(list, node_create(13)); list_insert(list, node_create(8)); list_insert(list, node_create(11)); list_print(list); Node *node = list_search(list, 8); list_delete(list, node); list_print(list); list_destory(list); return 1; }