小編這次要給大家分享的是C++模板如何實現(xiàn)順序棧,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
創(chuàng)新互聯(lián)是一家專業(yè)提供大同企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站建設(shè)、成都做網(wǎng)站、H5頁面制作、小程序制作等業(yè)務(wù)。10年已為大同眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進行中。
順序棧:利用一組連續(xù)的存儲單元依次存放自棧底到棧頂?shù)臄?shù)據(jù)元素;由于棧頂元素是經(jīng)常變動的,所以附設(shè)top指示棧頂元素在順序表中的位置,同時也需要知道順序棧存儲空間的起始位置,因此還需設(shè)定一個base指針用來指示??臻g的起始位置。
一般約定top指針指向棧頂元素的下一個位置,即新數(shù)據(jù)元素將要插入得位置。
下面我們使用模板簡單實現(xiàn)一個順序棧:
SeqStack.h
template<typename Type> class SeqStack{ public: SeqStack(int sz):m_ntop(-1),m_nMaxSize(sz){ m_pelements=new Type[sz]; if(m_pelements==NULL){ cout<<"Application Error!"<<endl; exit(1); } } ~SeqStack(){ delete[] m_pelements; } public: void Push(const Type item); //push data Type Pop(); //pop data Type GetTop() const; //get data void Print(); //print the stack void MakeEmpty(){ //make the stack empty m_ntop=-1; } bool IsEmpty() const{ return m_ntop==-1; } bool IsFull() const{ return m_ntop==m_nMaxSize-1; } private: int m_ntop; Type *m_pelements; int m_nMaxSize; }; template<typename Type> void SeqStack<Type>::Push(const Type item){ if(IsFull()){ cout<<"The stack is full!"<<endl; return; } m_pelements[++m_ntop]=item; } template<typename Type> Type SeqStack<Type>::Pop(){ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } return m_pelements[m_ntop--]; } template<typename Type> Type SeqStack<Type>::GetTop() const{ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } return m_pelements[m_ntop]; } template<typename Type> void SeqStack<Type>::Print(){ cout<<"bottom"; for(int i=0;i<=m_ntop;i++){ cout<<"--->"<<m_pelements[i]; } cout<<"--->top"<<endl<<endl<<endl; }
Main.cpp
#include<iostream> using namespace std; #include "SeqStack.h" int main(){ SeqStack<int> stack(10); int init[10]={1,2,6,9,0,3,8,7,5,4}; for(int i=0;i<10;i++){ stack.Push(init[i]); } stack.Print(); stack.Push(88); cout<<stack.Pop()<<endl; stack.Print(); stack.MakeEmpty(); stack.Print(); stack.Pop(); return 0; }
看完這篇關(guān)于C++模板如何實現(xiàn)順序棧的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。
文章題目:C++模板如何實現(xiàn)順序棧
轉(zhuǎn)載來于:http://jinyejixie.com/article40/pgisho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、營銷型網(wǎng)站建設(shè)、建站公司、ChatGPT、云服務(wù)器、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)