想使栈里的元素是字符型的
//Stack.h
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef STACK_H
#define STACK_H
class Stack
{
public:
Stack();
~Stack();
bool isEmpty();//判断栈是否为空
int getTop(char &d);//获得最上面的元素
int pop(char &d);//将最上面的元素弹出
int push(char d);//将指定元素压入栈
private:
enum{STACK_INIT_SIZE = 10,STACK_INCREMENT = 2};
char* base;//栈底指针
char* top;//栈顶指针
int stackSize;//栈的大小
void initialize();//初始化栈
void destroy();//销毁栈
};
#endif
//Stack.cpp
#include "Stack.h"
//构造函数
Stack::Stack()
{
initialize();
}
//析构函数
Stack::~Stack()
{
destroy();
}
//初始化
void Stack::initialize()
{
base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if(!base)
exit(0);
top = base;
stackSize = STACK_INIT_SIZE;
}
//销毁
void Stack::destroy()
{
base = top = NULL;
stackSize = 0;
}
//栈是否为空
bool Stack::isEmpty()
{
if(base == top)
return true;
else
return false;
}
//获得栈顶元素
int Stack::getTop(char &d)
{
if(base == top)
return 0;
else
d = *(top - 1);
return 1;
}
//出栈
int Stack::pop(char &d)
{
if(base == top)
return 0;
d = *(top - 1);
top--;
return 1;
}
//入栈
int Stack::push(char d)
{
if(top - base >= stackSize)
{
base = (char*)realloc(base,(stackSize + STACK_INCREMENT) * sizeof(char));
if(!base)
exit(0);
top = base + stackSize;
stackSize += STACK_INCREMENT;
}
*top = d;
top++;
return 1;
}