栈的顺序存储结构称为顺序栈,下面是顺序栈的实现:
/*
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;
}
有什么问题或错误的地方请大家指出来,互相学习,谢谢.........