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

一 问题描述

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

  1. 有序二叉树形如:
              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[N];
		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定义了局部静态变量。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值