C++模板實現(xiàn)順序棧
順序棧:利用一組連續(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; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++?Cartographer源碼中關(guān)于傳感器的數(shù)據(jù)傳遞實現(xiàn)
這篇文章主要介紹了C++?Cartographer源碼中關(guān)于傳感器的數(shù)據(jù)傳遞實現(xiàn),前面已經(jīng)談到了Cartographer中添加軌跡的方法和傳感器的數(shù)據(jù)流動走向。發(fā)現(xiàn)在此調(diào)用了LaunchSubscribers這個函數(shù)來訂閱相關(guān)傳感器數(shù)據(jù)2023-03-03C++中回調(diào)函數(shù)及函數(shù)指針的實例詳解
這篇文章主要介紹了C++中回調(diào)函數(shù)及函數(shù)指針的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解掌握這部分內(nèi)容,需要的朋友可以參考下2017-10-10Cocos2d-x學(xué)習(xí)筆記之CCScene、CCLayer、CCSprite的默認(rèn)坐標(biāo)和默認(rèn)錨點實驗
這篇文章主要介紹了Cocos2d-x學(xué)習(xí)筆記之CCScene、CCLayer、CCSprite的默認(rèn)坐標(biāo)和默認(rèn)錨點實驗,這是一個非常值得研究的問題,需要的朋友可以參考下2014-09-09從匯編看c++中函數(shù)里面的static關(guān)鍵字的使用說明
c++中的static關(guān)鍵字使得函數(shù)里面的局部變量的存活期不在局限于函數(shù)里面,而是變?yōu)樵谡麄€程序生命期里面都有效2013-05-05