スタック C++ の実装

目次

スタックの実装

応用例

演算結果


スタックの実装

#include <iostream>
using namespace std;

#define MaxSize 100
#define Elem int
#define ERROR -1

typedef  struct SNode *Stack;
struct SNode{
    int data[MaxSize];
    int Top=-1;
};
///加入元素
void Push(Stack Ptr,Elem item){
    if(Ptr->Top==MaxSize-1){
        cout<<"堆栈满"<<endl;return;
    }else{
        Ptr->data[++Ptr->Top]=item;
    }
}
///删除元素
Elem Pop(Stack Ptr){
    if(Ptr->Top==-1){
        cout<<"堆栈空"<<endl;
        return ERROR;
    } else{
        return Ptr->data[Ptr->Top--];
    }

}

応用例

///实例
int main()
{
    Stack stack=new SNode;
    cout<<Pop(stack)<<endl;
    Push(stack,2);
    cout<<Pop(stack)<<endl;
    return 0;
}

 

演算結果

 

おすすめ

転載: blog.csdn.net/qq_62477821/article/details/123431911