棧的實現,包含的函數有Top(), Push(), Pop().
簡單易懂的代碼~
實現代碼:
~~~
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
template <class T>
class Stack
{
public:
virtual bool IsEmpty() const = 0; // 判斷棧是否為空 為空則返回true
virtual bool IsFull() const = 0; // 判斷棧是否滿 滿則返回true
virtual bool Top(T &x) const = 0; // 返回棧頂元素 操作成功則返回true
virtual bool Push(T x) = 0; // 入棧 操作成功則返回true
virtual bool Pop() = 0; // 出棧 操作成功則返回true
virtual void Clear() = 0; // 清除棧中所有元素
/* data */
};
template <class T>
class SeqStack: public Stack<T>
{
public:
SeqStack(int mSize);
~SeqStack() { delete []s; }
bool IsEmpty() const { return top == 1; }
bool IsFull() const { return top == maxTop; }
bool Top(T &x) const;
bool Push(T x);
bool Pop();
void Clear() { top = -1; }
/* data */
private:
int top, maxTop; // 棧頂指針 最大棧頂指針
T *s;
};
template <class T>
SeqStack<T>::SeqStack(int mSize)
{
maxTop = mSize - 1;
s = new T[mSize];
top = 1;
}
template <class T>
bool SeqStack<T>::Top(T &x) const
{
if(IsEmpty()) {
cout << "Stack is empty" << endl;
return false;
}
x = s[top];
return true;
}
template <class T>
bool SeqStack<T>::Push(T x)
{
if(IsFull()) {
cout << "Stack is full" << endl;
return false;
}
s[++top] = x;
return true;
}
template <class T>
bool SeqStack<T>::Pop()
{
if(IsEmpty()) {
cout << "Stack is empty" << endl;
return false;
}
top--;
return true;
}
int main(int argc, char const *argv[])
{
SeqStack<int> s(5);
for(int i = 0; i < 3; ++i)
s.Push(i); // s包含0 1 2
int x;
if(s.Top(x)) cout << "The top of s is " << x << endl;
if(s.Push(x)) cout << "Push successfully" << endl;
if(s.Pop()) cout << "Pop successfully" << endl;
s.Clear();
return 0;
}
~~~
- 前言
- 線性表的順序表示:順序表ADT_SeqList
- 結點類和單鏈表ADT_SingleList
- 帶表頭結點的單鏈表ADT_HeaderList
- 堆棧的順序表示ADT_SeqStack
- 循環隊列ADT_SeqQueue
- 一維數組ADT_Array1D
- 稀疏矩陣ADT_SeqTriple
- 數據結構實驗1(順序表逆置以及刪除)
- 數據結構實驗1(一元多項式的相加和相乘)
- 二叉樹ADT_BinaryTree
- 優先隊列ADT_PrioQueue
- 堆ADT_Heap
- 數據結構實驗2(設計哈弗曼編碼和譯碼系統)
- ListSet_無序表搜索
- ListSet_有序表搜索
- ListSet_對半搜索的遞歸算法
- ListSet_對半搜索的迭代算法
- 二叉搜索樹ADT_BSTree
- 散列表ADT_HashTable
- 圖的鄰接矩陣實現_MGraph
- 圖的鄰接表實現_LGraph
- 數據結構實驗2(二叉鏈表實現二叉樹的基本運算)
- 數據結構實驗3(圖的DFS和BFS實現)
- 數據結構實驗3(飛機最少環城次數問題)
- 拓撲排序的實現_TopoSort
- 數據結構實驗4(排序算法的實現及性能分析)