棧的陣列實現與連結串列實現
阿新 • • 發佈:2018-12-23
棧的說明
棧是一種基本的資料結構。在棧中,被刪除的元素是最近被插入的元素,實現的是一種後進先出(last-in, first-out, LIFO)的策略。
改變棧中元素的操作方法只有兩個——push與pop。push是把元素推入棧底,pop是把元素從棧頂彈出。
下面是push和pop的過程
圖片來自《Data Structures and Program Design In C++》
陣列實現
陣列實現的思想很簡單。利用一個變數count來記錄棧頂,然後對陣列進行操作。
圖片來自《Data Structures and Program Design In C++》
template <class T> class Stack { private: static const int maxstack = 10; T entry[maxstack]; int count; int stackSize; bool full() const { return stackSize == maxstack; } public: Stack() : count(0), stackSize(0) { for (int i = 0; i < maxstack; i++) entry[i] = T(); } void push(const T &val) { if (!full()) { entry[count] = val; ++count; ++stackSize; } } void pop() { if (!empty()) { --count; --stackSize; } } T top() const { if (!empty()) return entry[count - 1]; } bool empty() const { return stackSize == 0 && count == 0; } int size() const { return stackSize; } };
連結串列實現
連結串列實現是以一個top_node作為連結串列的表頭,標記棧頂,在此進行插入和刪除操作
圖片來自《Data Structures and Program Design In C++》
圖片來自《Data Structures and Program Design In C++》
圖片來自《Data Structures and Program Design In C++》
template <class T> class Stack { private: // 宣告結點的結構體 struct Node { T data; Node *next; }; private: Node *top_node; int stackSize; public: Stack() : top_node(NULL), stackSize(0) { } ~Stack_List() { while (!empty()) pop(); } // push將新來的元素新增到連結串列頭 void push(const T &val) { Node *new_node = new Node; new_node->data = val; new_node->next = top_node; top_node = new_node; ++stackSize; } // pop把連結串列頭即棧頂的元素彈出 void pop() { if (!empty()) { Node *temp = top_node; top_node = top_node->next; delete temp; --stackSize; } } T top() const { return top_node->data; } bool empty() const { return stackSize == 0 && top_node == NULL; } int size() const { return stackSize; } };
簡單測試
#include <iostream>
using namespace std;
int main() {
Stack<int> s;
for (int i = 0; i < 11; i++)
s.push(i);
cout << s.size() << endl;
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}
陣列實現的棧的測試結果
由於設定棧的最大容量為10,因此只有10個元素在棧內
連結串列實現的棧的測試結果
由於連結串列的長度是可增長的,因此能有11個元素在棧內
參考書籍
《Data Structures and Program Design In C++》