C++棧(stack)的模板類(lèi)實(shí)現(xiàn)代碼
本文實(shí)例為大家分享了C++棧(stack)的模板類(lèi)實(shí)現(xiàn)代碼,供大家參考,具體內(nèi)容如下
1.基本概念
棧中的元素遵守“先進(jìn)后出”的原則(LIFO,Last In First Out)
只能在棧頂進(jìn)行插入和刪除操作
壓棧(或推入、進(jìn)棧)即push,將數(shù)據(jù)放入棧頂并將棧頂指針加一
出棧(或彈出)即pop,將數(shù)據(jù)從棧頂刪除并將棧頂指針減一
棧的基本操作有:pop,push,判斷空,獲取棧頂元素,求棧大小
2.構(gòu)造棧
可以使用數(shù)組構(gòu)造棧,也可以使用單向鏈表構(gòu)造,我覺(jué)得使用單向鏈表更加靈活方便,下面的例子我使用單向鏈表來(lái)構(gòu)造棧。
單向鏈表的頭插法比較適合,鏈表頭作為棧頂:
節(jié)點(diǎn)的數(shù)據(jù)結(jié)構(gòu):
template<class T> struct node { T value; //儲(chǔ)存的值 node<T>* next; node() :next(nullptr){} //構(gòu)造函數(shù) node(T t) :value(t), next(nullptr){} };
用模板類(lèi)構(gòu)造一個(gè)簡(jiǎn)單的stack類(lèi):
template<class T> class myStack { int cnts; //入棧數(shù)量 node<T> *head; //棧的頭部 public: myStack(){ cnts = 0; head = new node<T>; } void stackPush(T arg); //入棧 T stackPop(); //出棧 T stackTop(); //獲取棧頂元素 void printStack(); //打印棧 int counts(); //獲取棧內(nèi)元素個(gè)數(shù) bool isEmpty(); //判斷空 }; template<class T> void myStack<T>::stackPush(T arg) { node<T> *pnode = new node<T>(arg); //申請(qǐng)入棧元素的空間 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
OpenCV實(shí)現(xiàn)區(qū)域分割和區(qū)域生長(zhǎng)
區(qū)域分割是圖像處理中一個(gè)重要的任務(wù),本文主要介紹了OpenCV實(shí)現(xiàn)區(qū)域分割和區(qū)域生長(zhǎng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02C++ CryptoPP使用AES實(shí)現(xiàn)加解密詳解
Crypto++ (CryptoPP) 是一個(gè)用于密碼學(xué)和加密的 C++ 庫(kù),提供了大量的密碼學(xué)算法和功能,這篇文章主要為大家介紹了C++ CryptoPP如何使用AES實(shí)現(xiàn)加解密,需要的可以參考下2023-11-11c++連接mysql5.6的出錯(cuò)問(wèn)題總結(jié)
下面小編就為大家?guī)?lái)一篇c++連接mysql5.6的出錯(cuò)問(wèn)題總結(jié)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,祝大家游戲愉快哦2016-12-12C++ virtual destructor虛擬析構(gòu)函數(shù)
C++中基類(lèi)采用virtual虛析構(gòu)函數(shù)是為了防止內(nèi)存泄漏。具體地說(shuō),如果派生類(lèi)中申請(qǐng)了內(nèi)存空間,并在其析構(gòu)函數(shù)中對(duì)這些內(nèi)存空間進(jìn)行釋放,今天通過(guò)本文給大家介紹C++ virtual destructor虛擬析構(gòu)函數(shù)的相關(guān)知識(shí),感興趣的朋友一起看看吧2021-05-05