C++模板實現(xiàn)順序棧
順序棧:利用一組連續(xù)的存儲單元依次存放自棧底到棧頂?shù)臄?shù)據(jù)元素;由于棧頂元素是經(jīng)常變動的,所以附設top指示棧頂元素在順序表中的位置,同時也需要知道順序棧存儲空間的起始位置,因此還需設定一個base指針用來指示棧空間的起始位置。
一般約定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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++實現(xiàn)LeetCode(126.詞語階梯之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(126.詞語階梯之二),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
C語言雙指針多方法旋轉(zhuǎn)數(shù)組解題LeetCode
這篇文章主要為大家介紹了C語言雙指針使用多方法旋轉(zhuǎn)數(shù)組題解LeetCode,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-02-02
C++任意線程通過hwnd實現(xiàn)將操作發(fā)送到UI線程執(zhí)行
做Windows界面開發(fā)時,經(jīng)常需要在多線程環(huán)境中將操作拋到主線程執(zhí)行,下面我們就來學習一下如何在不需要重新定義消息以及接收消息的情況下實現(xiàn)這一要求,感興趣的可以了解下2024-03-03
C++實現(xiàn)將數(shù)據(jù)寫入Excel工作表的示例代碼
直觀的界面、出色的計算功能和圖表工具,使Excel成為最流行的個人計算機數(shù)據(jù)處理軟件。在本文中,您將學習如何使用?Spire.XLS?for?C++?創(chuàng)建?Excel?文檔,以及如何將數(shù)據(jù)寫入?Excel?工作表2023-03-03

