【课程资料】栈(c++实现)

现在上传一份可以使用的栈的代码,方便童鞋们参考。

这个代码是将一个数组中的元素依次压入栈中,然后弹出。

可以使用这段代码来完成第二次作业。

P.S. 代码略丑,勿喷。

#include <iostream>

using namespace std;

#define MAXSIZE 100001

template<class type>
class SeqStack
{
	private:
		int	top; // 栈顶指针 
		type*	_stack; // 数组名 
		int	maxsize; // 栈最大可容纳元素个数
	public:
		SeqStack();
		SeqStack(int size);
		virtual ~SeqStack()
		{
			delete []_stack;
		}
		void Push(const type &item);
		type Pop();
		type Top();
		/*
		 * Empty()
		 * 判断栈是否为空
		 */
		int Empty() const
		{
			if ( -1 == top ){
				return true;
			}else {
				return false;
			}
		}

		/*
		 * Full()
		 * 判断栈是否满了
		 */
		int Full() const
		{
			if ( maxsize - 1 == top ){
				return true;
			} else {
				return false;
			}
		}

		/*
		 * Clear()
		 * 将栈里的元素清空
		 */
		void Clear()
		{
			top=-1;
		}
}; 

/*
 * SeqStack()
 * 构造函数
 */
template <class type>
SeqStack<type>::SeqStack():
	top(-1),maxsize(MAXSIZE)
{
	_stack = new type[maxsize];
	if ( _stack == NULL ){
		cerr<<"allocate failed!"<<endl;
		exit(1);
	}
}

template <class type> 
SeqStack<type>::SeqStack(int size):
	top(-1),maxsize(size)
{
	_stack = new type[maxsize];
	if ( _stack == NULL ){
		cerr<<"allocate failed!"<<endl;
		exit(1);
	}
} 

/*
 * Pop()
 * 弹出栈顶元素
 */
template <class type> 
type SeqStack<type>::Pop()
{
	if ( Empty() ){
		cerr<<"Empty!"<<endl;
		exit(1);
	}
	
	type data = _stack[top];
	top--;
	return data;
}

/*
 * Top()
 * 返回栈顶元素
 */
template <class type>
type SeqStack<type>::Top()
{
	if ( Empty() ){
		cerr<<"Empty!"<<endl;
		exit(1);
	}
	
	return _stack[top];
}

/*
 * Push()
 * 在栈中加入一个元素
 */
template <class type>
void SeqStack<type>::Push(const type &item )
{
	if ( Full() ) {
		cerr<<"Full!"<<endl;
		exit(1);
	}
	
	_stack[++top] = item;
}

int main()
{
	int num[10]={1,2,3,4,5,6,7,8,9,10};
	SeqStack<int> stack(10);
	for ( int i=0;i<10;i++){
		//依次向栈中加入元素 
		stack.Push(num[i]);
	}
	while ( !stack.Empty() ){
		//依次弹出栈顶的元素 
		cout<<stack.Pop()<<" ";
	}cout<<endl;
	getchar();getchar();
	return 0;
}
--Carwest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值