双向循环链表和树

来源:互联网 发布:php时间戳代码 编辑:程序博客网 时间:2024/06/04 19:02

一、实现双向循环链表的基本操作。

有了链表的基础,双向循环链表也比较容易实现,只是其插入与删除操作稍微复杂一点。

 

如图,需要插入一个新的节点,则需按照如图的顺序做相应的改变即可。

node->front = L;

node->next = L->next;

L->next = node;

node->next->front = node;

当然,顺序很重要,否则有可能会造成“锻炼”的情况。删除节点同样需要注意顺序。

 

 

#include<stdio.h>#include"double_list.h"#include<malloc.h>typedef int data_t;typedef struct LIST LIST{data_t data;LIST *front;LIST *next;};LIST *create_list();void insert_list(LIST *,data_t);void del_list(LIST *,data_t );void show_list(LIST *);void show_dlist(LIST *L, int flage);LIST *create_list(){LIST *L = malloc(sizeof(LIST));L->front = L->next = L;//初始化时将front和next都指向自己return L;}void insert_list(LIST *L,data_t data)  //从头插入 {LIST *node = malloc(sizeof(LIST));node->data = data;node->front = L;node->next = L->next;L->next = node;node->next->front = node;}void del_list(LIST *L,data_t data){LIST *t;      //用于缓存删除节点的地址,使用free()释放内存LIST *t2 = L;while(L->next != t2)  //条件不满足时遍历到第一个元素{if(L->next->data == data){t = L->next;L->next = L->next->next;L->next->front = L;break;}L = L->next;}free(t);}void show_dlist(LIST *L, int flage){LIST *t = L;if(FOR == flage)   //从前往后遍历{while(L->next != t){printf("%d ", L->next->data);L = L->next;}}else        //从后往前变量{while(L->front != t){printf("%d ", L->front->data);L = L->front;}}printf("\n");}


二、创建一颗二叉查找数,实现先序遍历、中序遍历、后序遍历和按层遍历的基本操作。

按层遍历时,我们可以借助队列实现,首先根节点地址入队,每一个节点地址出队列时,输出节点元素,判断是否有左子树,有者左子树地址进入队,再判断否有右子树,有者右子树地址进入队,如此循环,直到队列为空。

队列昨天已实现,今天直接调用即可。

#include "queue.h"#include <malloc.h>#include <stdio.h>typedef struct tree{data_t data;struct tree *l, *r;}TREE;typedef int data_t;TREE *create_tree(data_t *data, int len);void DLR(TREE *root);void LDR(TREE *root);void LRD(TREE *root);void layer_show(TREE *root);static TREE *create_tree_node(data_t data){TREE *node = malloc(sizeof(TREE));node->data = data;node->l = node->r = NULL;return node;}TREE *create_tree(data_t *data, int len){TREE *root = create_tree_node(data[0]), *node, *t;t = root;int i = 1;for(;i<len; i++){node = create_tree_node(data[i]);root = t;while(1){if(node->data <= root->data){if(root->l == NULL){root->l = node;break;}elseroot = root->l;}else{if(root->r == NULL){root->r = node;break;}elseroot = root->r;}}}return t;}void DLR(TREE *root){if(NULL == root)return;printf("%d ", root->data);DLR(root->l);DLR(root->r);}void LDR(TREE *root){if(NULL == root)return;LDR(root->l);printf("%d ", root->data);LDR(root->r);}void LRD(TREE *root){if(NULL == root)return;LRD(root->l);LRD(root->r);printf("%d ", root->data);}void layer_show(TREE *root){TREE *t1 = malloc(sizeof(TREE));QUE *Q = create_que();en_que(Q, (data_t)root);while(!isnull_que(Q)){t1 = (TREE *)out_que(Q);printf("%d ",t1->data);if(t1->l)en_que(Q, (data_t)(t1->l));if(t1->r)en_que(Q, (data_t)(t1->r));}}


 

0 0