数据结构——c双向链表实现
不带头结点
#include<stdlib.h> typedef struct _tlist{ int data; struct _tlist *prior; struct _tlist *next; } *TList, TNode; void initTList(TList *l) { *l = NULL; } void insertToHead(TList *l, int val) { TList temp = (TList)malloc(sizeof(TNode)); TList t = *l; // 如果链表为NULL if(t == NULL) { temp->data = val; temp->prior = NULL; temp->next = NULL; *l = temp; return; } temp->data = val; temp->prior = NULL; temp->next = t; t->prior = temp; *l = temp; } void insertToTail(TList *l, int val) { TList temp = (TList)malloc(sizeof(TNode)); TList t = *l; if(t == NULL) { temp->data = val; temp->prior = NULL; temp->next = NULL; *l = temp; return; } temp->data = val; // 找到旧双向链表的最后一个结点,t 指向最后一个结点 // 使用 t && t->next 条件 while(t && t->next) t = t->next; t->next = temp; temp->prior = t; temp->next = NULL; } void deleteTListHead(TList *l) { if(*l == NULL) return; TList t = *l; // t指向头结点 *l = t->next; free(t); } void printTList(TList l, const char* str) { if(str != NULL) printf("%s\n",str); while(l) { printf("%3d", l->data); l = l->next; } printf("\n"); }
运行结果如下:
$ ./TList 从双向链表头部插入5,6 6 5 从双向链表尾部插入7,8 6 5 7 8 删除双向链表的第一个结点 5 7 8
一干解千愁

浙公网安备 33010602011771号