通过表达式构造二叉树 c++

折腾了好久终于把这个程序完善了。

二叉树的定义就不再啰嗦了。

这个程序注意的地方有如下几个:

1. 节点存储的可能是数,可能是符号,因此数据要做区分。

2. 操作符优先级,括号要特殊处理。

代码如下

Stack.h:

#ifndef STACK_H_
#define STACK_H_
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5
#ifndef Status
#define Status int
#define OK 1
#define ERROR 0
#define OVERFLOW 2
#endif
#include<cstdlib>
#include<malloc.h>
template<class sElemType>
class Stack
{
private:
	sElemType* base;
	sElemType* top;
	int stacksize;
public:
	Stack();
	~Stack();
	Status ClearStack();
	bool StackEmpty();
	int StackLength() { return stacksize; }
	Status GetTop(sElemType & e);
	Status Push(sElemType e);
	Status Pop(sElemType & e);
	Status StackTraverse(Status(*visit)(sElemType t));
};
template<class sElemType>
Stack<sElemType>::Stack()
{
	base = (sElemType*)malloc(STACK_INIT_SIZE*sizeof(sElemType));
	if (!base) exit(OVERFLOW);
	top = base;
	stacksize = STACK_INIT_SIZE;
}
template<class sElemType>
Status Stack<sElemType>::GetTop(sElemType & e)
{
	if (top == base) return ERROR;
	e = *(top - 1);
	return OK;
}
template<class sElemType>
Status Stack<sElemType>::Push(sElemType e)
{
	if (top - base >= stacksize)
	{
		base = (sElemType*)realloc(base, sizeof(sElemType)*(stacksize + STACKINCREMENT));
		if (!base) exit(OVERFLOW);
		top = base + STACKINCREMENT;
		stacksize += STACKINCREMENT;
	}
	*top++ = e;
	return OK;
}
template<class sElemType>
Status Stack<sElemType>::Pop(sElemType & e)
{
	if (top 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值