这样定义栈结构可以吗?

weiyiabout 2008-05-08 09:23:45
想使栈里的元素是字符型的


//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;
}
...全文
207 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lisheng053758 2008-05-09
  • 打赏
  • 举报
回复
这样行呀
你若想用c++实现的话,有现成的Stack类。
只要写上using namespace std;就行了,不过是个模板类。
phidemon 2008-05-09
  • 打赏
  • 举报
回复
想你所想,顶一个!
fire_woods 2008-05-09
  • 打赏
  • 举报
回复
只发现有内存泄漏
还有恐怖的exit(0);

这两个问题,其他的米仔细看.

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧