您的位置:首页 > 其它

静态变量的应用--将二叉排序树转换为有序的双向链表输出

2013-11-17 15:05 357 查看
一 问题描述

给出一颗有序二叉树,将它转换为有序的双向链表输出。

有序二叉树形如:

          10

          /   \

        6     14

      /   \    /    \

    4    8 12  16

双向链表形如:

4=6=8=10=12=14=16

二 解题思路



如上图所示,

第一,建立二叉排序树BST

第二,中序遍历BST逐步生成双向链表

 三 测试



四 代码

/*
* change a bst to Double linked list
*/
#include <stdio.h>
#include <stdlib.h>

#define N 10
typedef int ElemType;
typedef struct BSTNode {
ElemType data;
struct BSTNode *lchild;
struct BSTNode *rchild;
}BSTNode;

typedef struct DLinkNode {
ElemType data;
struct DLinkNode *llink;
struct DLinkNode *rlink;
}DLinkNode;
DLinkNode *head;
void InsertBST(BSTNode **t, ElemType e) {
if(*t == NULL) {
*t = (BSTNode *)calloc(1, sizeof(BSTNode));
if(*t == NULL) {
fprintf(stderr, "memeory eror!\n");
exit(254);
}
// *t = (BSTNode *)malloc(sizeof(BSTNode));
(*t)->lchild = 0;
(*t)->rchild = 0;
(*t)->data = e;
}
else if((*t)->data > e) InsertBST(&(*t)->lchild, e);
else InsertBST(&(*t)->rchild, e);
}
void PostTranverse(BSTNode *t) {
if(t) {
PostTranverse(t->lchild);
// printf("%d\t", t->data);
CreateDLinkList(t->data);
PostTranverse(t->rchild);
}
}
/*
* to create a double linked list
*/
void CreateDLinkList(ElemType e) {
static DLinkNode *r; // be defined in the static area of RAM
if(!head) {
head = (DLinkNode *)calloc(1, sizeof(DLinkNode));
if(head == NULL) {
fprintf(stderr, "memory error!\n");
exit(254);
}
head->llink = 0;
head->rlink = 0;
r = head;
}
DLinkNode *p = (DLinkNode *)calloc(1, sizeof(DLinkNode));
if(p == NULL) {
fprintf(stderr, "memory error!\n");
exit(254);
}
p->data = e;
p->llink = r;
p->rlink = 0;
r->rlink = p;
r = p;
}
int main() {
int a
;
int i;
BSTNode *t = NULL;
DLinkNode *p;
for(i = 0;i < N;i++) {
if(scanf("%d", &a[i]) != 1) {
fprintf(stderr, "input error!\n");
exit(EXIT_FAILURE);
}
}
for(i = 0;i < N;i++) {
InsertBST(&t, a[i]);
}
PostTranverse(t);
p = head->rlink;
while(p) {
printf("%d\t", p->data);
p = p->rlink;
}
printf("\n");
return 0;
}

五 编程体会
    为了实现松耦合。PostTranverse只是传递每次遍历的结点中的数值给CreateDLinkList函数,而为了持续生成双向链表,可以把head定义为全局变量,r定义了局部静态变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐