#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////
int const OK=1;
int const FALSE=0;
int const TRUE=1;
int const ERROR=0;
int const INFEASIBLE=-1;
typedef int Status;
///////////////////////////////////////////////////////////
const int STACK_INIT_SIZE=6; //存储空间初始分配量
template<class type>
class SqStack
{
public:
SqStack();//构造一个空栈
~SqStack();//销毁栈
Status ClearStack();//把栈清空
Status StackEmpty();//判断栈是否为空。若空,返回TRUE;若不空,返回FALSE;
int StackLength();//返回栈的长度
void GetTop(type& e);//若栈不空,用e返回栈顶元素
Status Push(type e);//插入元素e为栈顶元素
Status Pop(type& e);//若栈不空,删除栈顶元素,用e返回其值
private:
type *base;
type *top;
int stacksize;
};
template<class type>
SqStack<type>::SqStack():stacksize(STACK_INIT_SIZE)
{
base=new type[stacksize];
if(!base)
{
cerr<<"动态存储分配失败!"<<endl;
exit(1);
}
top=base;
}
template<class type>
SqStack<type>::~SqStack()
{
delete[] base;
base=0;
top=base;
}
template<class type>
Status SqStack<type>::ClearStack()
{
top=base;
return OK;
}
template<class type>
Status SqStack<type>::StackEmpty()
{
return (top==base)?TRUE:FALSE;
}
template<class type>
int SqStack<type>::StackLength()
{
return (top-base);//原先这里出问题,是因为写成了(top-base)/sizeof(type)
}
template<class type>
void SqStack<type>::GetTop(type& e)
{
if(top!=base)
e=*(top-1);
else{
cout<<"栈空!"<<endl;
}
}
template<class type>
Status SqStack<type>::Push(type e)
{
if((top-base)>=stacksize)
{
cout<<"栈满!"<<endl;
return ERROR;
}else{
*top=e;
top++;
cout<<"添加成功~"<<endl;
return OK;
}
}
template<class type>
Status SqStack<type>::Pop(type& e)
{
if(base==top){
cerr<<"栈已空!"<<endl;
return ERROR;
}else{
e=*(--top);
return OK;
}
}
/*
SqStack();//构造一个空栈
~SqStack();//销毁栈
Status ClearStack();//把栈清空
Status StackEmpty();//判断栈是否为空。若空,返回TRUE;若不空,返回FALSE;
int StackLength();//返回栈的长度
void GetTop(type& e);//若栈不空,用e返回栈顶元素
Status Push(type e);//插入元素e为栈顶元素
Status Pop(type& e);//若栈不空,删除栈顶元素,用e返回其值
*/
int main()
{
SqStack<int> stack;
if(stack.StackEmpty())
cout<<"栈空"<<endl;
stack.Push(1);
stack.Push(2);
stack.Push(3);
int len=stack.StackLength();
cout<<"栈长度为:"<<len<<endl;
//输出
int e=0;
for(int j=0;j<5;j++)
{
if(stack.Pop(e))
cout<<e;
}
cout<<endl;
len=stack.StackLength();
cout<<"栈长度为:"<<len<<endl;
system("pause");
return 0;
}
C++ 顺序栈(类模板实现)
最新推荐文章于 2022-11-10 20:14:48 发布
本文介绍如何使用C++模板类实现一个简单的栈结构,包括构造、销毁、清空、判空、获取栈顶元素、压栈、弹栈等基本操作。
307

被折叠的 条评论
为什么被折叠?



