C++ 顺序栈(类模板实现)

本文介绍如何使用C++模板类实现一个简单的栈结构,包括构造、销毁、清空、判空、获取栈顶元素、压栈、弹栈等基本操作。
#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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值