本文實例為大家分享了C++棧(stack)的模板類實現代碼,供大家參考,具體內容如下
1.基本概念
棧中的元素遵守“先進后出”的原則(LIFO,Last In First Out)
只能在棧頂進行插入和刪除操作
壓棧(或推入、進棧)即push,將數據放入棧頂并將棧頂指針加一
出棧(或彈出)即pop,將數據從棧頂刪除并將棧頂指針減一
棧的基本操作有:pop,push,判斷空,獲取棧頂元素,求棧大小
2.構造棧
可以使用數組構造棧,也可以使用單向鏈表構造,我覺得使用單向鏈表更加靈活方便,下面的例子我使用單向鏈表來構造棧。
單向鏈表的頭插法比較適合,鏈表頭作為棧頂:
節點的數據結構:
template<class T>struct node{ T value; //儲存的值 node<T>* next; node() :next(nullptr){} //構造函數 node(T t) :value(t), next(nullptr){}};
用模板類構造一個簡單的stack類:
template<class T>class myStack{ int cnts; //入棧數量 node<T> *head; //棧的頭部public: myStack(){ cnts = 0; head = new node<T>; } void stackPush(T arg); //入棧 T stackPop(); //出棧 T stackTop(); //獲取棧頂元素 void printStack(); //打印棧 int counts(); //獲取棧內元素個數 bool isEmpty(); //判斷空};template<class T>void myStack<T>::stackPush(T arg){ node<T> *pnode = new node<T>(arg); //申請入棧元素的空間 pnode->next = head->next; head->next = pnode; cnts++;}template<class T>T myStack<T>::stackPop(){ if (head->next!=nullptr) { node<T>* temp = head->next; head->next = head->next->next; T popVal = temp->value; delete temp; return popVal; }}template<class T>T myStack<T>::stackTop(){ if (head->next!=nullptr) { return head->next->value; }}template<class T>void myStack<T>::printStack(){ if (head->next != nullptr) { node<T>* temp = head; while (temp->next != nullptr) { temp = temp->next; cout << temp->value << endl; } }}template<class T>int myStack<T>::counts(){ return cnts;}template<class T>bool myStack<T>::isEmpty(){ if (cnts) return false; else return true;}
GitHub:https://github.com/whlook/stackTemplate
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選