1. 程式人生 > >實驗四:順序棧和鏈棧

實驗四:順序棧和鏈棧

#ifndef SeqStack_H
#define SeqStack_H
const int StackSize=10;
template
class SeqStack
{
	public:
		SeqStack();
		~SeqStack(){}
		void Push(DataType x);  //x入棧
		DataType Pop();   //將棧頂元素彈出
		DataType GetTop();  //取棧頂元素
		int Empty();  //判斷棧是否為空
	private:
		DataType data[StackSize];  //存放棧元素的陣列
		int top;                   //棧頂指標,指示棧頂元素在陣列中的下標
};
#endif


#include"SeqStack.h"

template
SeqStack::SeqStack()
{
	top=-1;
}

template
void SeqStack::Push(DataType x)
{
	if(top==StackSize-1)throw"上溢";
	top++;
	data[top]=x;
}

template
DataType SeqStack::Pop()
{
	DataType x;
	if(top==-1)throw"下溢";
	x=data[top--];
	return x;
}

template
DataType SeqStack::GetTop()
{
	if(top!=-1)
		return data[top];
}

template
int SeqStack::Empty()
{
	if(top==-1)return 1;
	else return 0;
}


#include
using namespace std;            //引入輸入輸出流
#include"SeqStack.cpp"           //引入類SeqStack的成員函式定義

void main()                   //主函式
{
	SeqStackS;            //建立模板類的例項
	if(S.Empty())
		cout<<"棧為空"<