我們用一個問題來說。問題是這樣的:
實現一個序列,該序列中包含n個棧Si (i = 1, 2, 3, ... , n),棧中存放的都是int類型的整數,並能夠完成以下操作:
-
push(t, x) 將元素x加入到棧St中,並返回元素x,即入棧操作。
-
top(t) 顯示棧St的最后一個元素。若棧為空,則什么都不做。
-
pop(t) 將棧St的最后一個元素刪除,並返回最后一個元素,即出棧操作。若棧為空,則什么都不做。
(為了簡單,沒有對類分離,寫在了一個文件里,有興趣的小伙伴們可以嘗試着將類分離開)
第一種方法:向量
由於向量直接提供了類似的 入棧和出棧函數,所以我想創建一個數組,數組中的元素是向量。每個向量就是一個棧。廢話不多說,上代碼:
#include <iostream> #include <vector> using namespace std; class stackTest { public: stackTest(int n){ stacks = new vector<int>[n]; cout << "棧創建成功!" << endl; } ~stackTest(){ delete[] stacks; cout << "棧銷毀成功!" << endl; } int push(int t, int x) { stacks[t-1].push_back(x); cout << "元素" << x << "入第" << t << "個棧" << endl; return x; } bool top(int t) { if (!stacks[t-1].empty()){ cout << "第" << t << "個棧的最后一個元素是" << stacks[t-1][stacks[t-1].size()-1] << endl; } return stacks[t-1].empty(); } int pop(int t) { int tmp = stacks[t-1][stacks[t-1].size()-1]; stacks[t-1].pop_back(); cout << "元素" << tmp << "出第" << t << "個棧" << endl; return tmp; } private: vector<int>* stacks; }; int main() { stackTest* s = new stackTest(2); cout << "----------------------------" << endl; s->push(1, 2); s->top(1); s->top(2); cout << "----------------------------" << endl; s->pop(1); s->top(1); cout << "----------------------------" << endl; delete s; return 0; }
運行結果:
第二種方法:結構體
用結構體實現棧,可以說是一般的方式了。代碼如下:
#include <iostream> using namespace std; const int STACKSIZE = 100; typedef struct{ int* base; int* top; int stack_size; }SqStack; bool initStack(SqStack& s) { s.base = new int[STACKSIZE]; if(!s.base){ cout << "初始化失敗" << endl; return false; }else{ s.top = s.base; s.stack_size = STACKSIZE; cout << "初始化成功" << endl; return true; } } int pushStack(SqStack& s, int x) { if(s.top-s.base >= s.stack_size){ cout << "棧滿,無法添加新元素" << endl; return -1; }else { *(s.top++) = x; return x; } } int popStack(SqStack& s){ if(s.top==s.base){ //cout << "棧為空" << endl; return -1; }else{ return *(--s.top); } } int topStack(SqStack& s) { if(s.top==s.base){ //cout << "棧為空" << endl; return -1; }else{ return *(s.top-1); } } class StackTest{ public: StackTest(int n){ stacks = new SqStack[n]; for (int i = 0; i < n; i++){ cout << i+1 << "號棧"; initStack(stacks[i]); } cout << "-------------------------" << endl; cout << n << "個棧創建完成!" << endl; } ~StackTest(){ delete[] stacks; cout << "棧銷毀完成!" << endl; } int push(int t, int x){ int tmp = pushStack(stacks[t-1], x); if(tmp != -1){ cout << t << "號棧元素" << tmp << "入棧" << endl;; } return tmp; } int pop(int t){ int tmp = popStack(stacks[t-1]); if(tmp != -1){ cout << t << "號棧元素" << tmp << "出棧" << endl;; } return tmp; } int top(int t){ int tmp = topStack(stacks[t-1]); if(tmp != -1){ cout << t << "號棧最后一個元素是" << tmp << endl;; } return tmp; } private: SqStack* stacks; }; int main() { StackTest* s = new StackTest(2); cout << "-------------------------" << endl; s->push(1, 2); s->top(1); s->top(2); cout << "-------------------------" << endl; s->pop(1); s->top(1); cout << "-------------------------" << endl; delete s; return 0; }
運行結果: