折腾了好久终于把这个程序完善了。
二叉树的定义就不再啰嗦了。
这个程序注意的地方有如下几个:
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