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

