#include <iostream>
//棧的數組實現
using namespace std;
#define MAXSIZE 10;
template<class T>
class Stack
{
public:
//默認構造函數
Stack();
Stack(size_t maxElements);
Stack(T data[], size_t maxElements);
~Stack();
//入棧
void Push(T data);
//出站並返回
T Pop();
//返回棧頂元素
T Top();
//判斷是否為空棧
bool isEmpty();
//棧是否已滿
bool isFull();
//清空棧
void Clear();
//獲得棧元素個數
size_t GetSize();
private:
//棧標指示器
size_t top;
//數組
T *arrays;
//棧的容量
size_t maxSize;
};
template<class T>
Stack<T>::Stack() : maxSize(MAXSIZE), top(-1)
{
arrays = new T[maxSize];
if (arrays == NULL)
{
cout << "動態分配內存失敗";
exit(1);
}
}
template<class T>
Stack<T>::Stack(size_t maxElements) : maxSize(maxElements), top(-1)
{
arrays = new T[maxSize];
if (arrays == NULL)
{
cout << "動態分配內存失敗";
exit(1);
}
}
template<class T>
Stack<T>::Stack(T data[], size_t maxElements) : maxSize(maxElements), top(-1)
{
arrays = new T[maxSize];//創建存儲棧的數組
if (arrays == NULL)
{
cout << "動態分配內存失敗";
exit(1);
}
for (size_t i = 0; i < maxSize; i++)
{
arrays[i] = data[i];
}
top += maxSize;
}
template<class T>
Stack<T>::~Stack()
{
delete[] arrays;
}
template<class T>
void Stack<T>::Push(T data)
{
if (isFull())
{
throw runtime_error("Full stack");
}
else
{
top++;//指向棧頂
arrays[top] = data;
}
}
template<class T>
T Stack<T>::Pop()
{
if (isEmpty())
{
throw runtime_error("No elements in the stack");
}
else
{
T data = arrays[top];
top--;
return data;
}
}
template<class T>
T Stack<T>::Top()
{
if (isEmpty())
{
throw runtime_error("No elements in the stack");
}
else
{
return arrays[top];
}
}
template<class T>
bool Stack<T>::isEmpty()
{
return top == -1;
}
template<class T>
bool Stack<T>::isFull()
{
return top == maxSize - 1;
}
template<class T>
void Stack<T>::Clear()
{
while (Top != -1)
{
Top--;
}
}
template<class T>
size_t Stack<T>::GetSize()
{
return top + 1;
}
int main()
{
try//異常捕獲
{
int a[6] = { 1, 2, 3, 4, 5, 6 };
Stack<int> s(a, 6);
s.Pop();
s.Push(7);
while (!s.isEmpty())
{
cout << s.Pop() << " ";
}
cout << endl;
}
catch (exception e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
測試運行結果:
來源:c++ 棧的數組實現