//---------------------------arrStack.h-----------------------------------
template <class T>
class arrStack
{
private: // 棧的順序存儲
int mSize; // 棧中最多可存放的元素個數
int top; // 棧頂位置,應小於mSize
T *data; // 存放棧元素的數組
public: // 棧的運算的順序實現
arrStack();
~arrStack();
arrStack(int size)
{ // 創建一個給定長度的順序棧實例
mSize = size; top = -1;
data = new T[mSize];
}
void clear(); // 變爲空棧
bool push(T const item); // item入棧,成功則返回真,否則返回假
bool pop(T & item); // 返回棧頂內容並彈出,成功返回真,否則返回假
bool getTop(T& item); // 返回棧頂內容但不彈出,成功返回真,否則返回假
bool isEmpty(); // 若棧已空返回真
bool isFull(); // 若棧已滿返回真
void print();
};
template <class T>
arrStack<T>::arrStack()
{ // 創建一個順序棧的實例
top = -1;
}
template <class T>
arrStack<T>::~arrStack()
{ // 析構函數
delete [] data;
//cout<<"調用析構函數!"<<endl;
}
template <class T>
void arrStack<T>::clear()
{ // 清空棧內容
top = -1;
}
template <class T>
bool arrStack<T>::push(T item)
{ // item入棧,成功則返回真,否則返回假
if(isFull())
{
cout<<"棧已滿!"<<endl;
return false;
}
else
{
data[++top]=item;
return true;
}
}
template <class T>
bool arrStack<T>::pop(T & item) // 返回棧頂內容並彈出,成功返回真,否則返回假
{
if(isEmpty())
{
cout<<"棧爲空!"<<endl;
return false;
}
else
{
item=data[top--];
return true;
}
}
template <class T>
bool arrStack<T>::getTop(T& item) // 返回棧頂內容但不彈出,成功返回真,否則返回假
{
if(isEmpty())
{
cout<<"棧爲空!"<<endl;
return false;
}
else
{
item=data[top];
return true;
}
}
template <class T>
bool arrStack<T>::isEmpty() // 若棧已空返回真
{
return (top==-1);
}
template <class T>
bool arrStack<T>::isFull() // 若棧已滿返回真
{
return (top==mSize-1);
}
template <class T>
void arrStack<T>::print() //輸出棧內容
{
for(int i=0;i<=top;i++)
cout<<data[i]<<" ";
cout<<endl;
}
*************************************arrStackMain.cpp**************************************************
#include "iostream"
#include "arrStack.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"-----------------------初始化棧------------------------"<<endl;
arrStack<int> obj(7);
int i;
int num;
int contant;
cout<<"請輸入需要初始化棧中的元素個數(小於等於7):";
cin>>num;
for(i=0;i<num;i++)
{
cout<<"請輸入第"<<i+1<<"個元素的值(以回車結束):";
cin>>contant;
obj.push(contant);
}
obj.print();
cout<<"------------------向棧中壓入元素13--------------------"<<endl;
obj.push(13);
obj.print();
cout<<"---------------------出棧操作-------------------------"<<endl;
obj.pop(contant);
cout<<"出棧的元素爲:"<<contant<<endl;
cout<<"-------------------返回棧頂元素-----------------------"<<endl;
obj.getTop(contant);
cout<<"棧頂元素爲:"<<contant<<endl;
cout<<"----------------------清空棧--------------------------"<<endl;
obj.clear();
if(obj.isEmpty())
cout<<"清空成功,棧爲空!"<<endl;
else
cout<<"清空失敗,棧不爲空!"<<endl;
cout<<"-------------------調用析構函數-----------------------"<<endl;
return 0;
}