C++类模板 实现顺序栈

栈的顺序存储结构称为顺序栈,下面是顺序栈的实现:

/*
Filename: SeqStack.h
Description: About the sequence of stack
Date: November 15, 2012
*/

#ifndef SEQSTACK_H
#define SEQSTACK_H

#include <iostream>
using namespace std;

const int StackSize = 10;

//顺序栈类定义
template<class T>
class SeqStack
{
public:
	SeqStack()
	{
		top = -1;
	}

	~SeqStack()
	{

	}

public:
	void Push(T x); //将元素x入栈
	T Pop();        //栈顶元素出栈
	T GetTop();		//读取栈顶元素
	bool Empty();
	void PrintStack();//打印栈内元素

private:
	T data[StackSize];
	int top;

};


//顺序栈类实现
template<class T>
void SeqStack<T>::Push(T x)
{
	if (top == StackSize-1)
	{
		throw "上溢";
	}
	
	data[++top] = x;
}


template<class T>
T SeqStack<T>::Pop()
{
	if (top == -1)
	{
		throw "下溢";
	}

	T x = data[top--];
	return x;

}


template<class T>
T SeqStack<T>::GetTop()
{
	if (top != -1)
	{
		return data[top];
	}
	
}


template<class T>
bool SeqStack<T>::Empty()
{
	if (top == -1 )
	{
		return true ;
	}
	
	return false;
}


template<class T>
void SeqStack<T>::PrintStack()
{
	if (!Empty())
	{
		int temp = top;
		while (temp != -1)
		{
			cout << data[temp] << " ";
			temp--;
		}
	}
	
	cout << endl;
}
#endif





#include "SeqStack.h"

int main()
{
	SeqStack<int> Ss;
	Ss.Push(2);
	Ss.Push(5);
	Ss.Push(7);
	Ss.Push(9);
	Ss.PrintStack();
	cout << "-------------------------" << endl;

	cout << "获得栈顶元素:" << Ss.GetTop() << endl;
	cout << "栈顶元素出栈:" << Ss.Pop() << endl;
	Ss.PrintStack();
	
	system("pause");
	return 0;
}


 有什么问题或错误的地方请大家指出来,互相学习,谢谢.........

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值