数据结构 c++栈的基本操作/初始化创建栈/入栈/出栈/判空/判满/获取栈顶元素

代码如下

#include <iostream>
#include<malloc.h>
#define MaxSize 10
using namespace std;

typedef int DataType;
typedef struct {
  DataType data[MaxSize];
  int top;
} SeqStack;
//创建顺序栈 初始化
SeqStack* createStack(SeqStack *S) {
    S = (SeqStack *)malloc(sizeof(SeqStack));
    S->top = -1;
    return S;
}
//判空
bool Empty(SeqStack *S) {
    if(S->top==-1)
        return true;  //栈为空
    return false;
}
//判满
bool Full_SeqStack(SeqStack *S)
{
    if(S->top == MaxSize -1)
        return true;
    return false;
}
//入栈
bool InitSert_SeqStack (SeqStack *S,DataType x)
{
    if(S->top == MaxSize - 1)
    {
        return false;
    }
    //S->top++;
    S->data[++S->top]=x;
    return true;
}
//出栈
bool pop(SeqStack *S, DataType x) {
    if(S->top == -1)
        return false;
    for(int i=0;i<MaxSize;i++)
    {
        x=S->data[S->top--];
        cout<<x<<" ";
    }
    return true;
}
//获取栈顶元素
bool GetTop(SeqStack *S, DataType x)
{
    if(S->top==-1)
        return false;
        x=S->data[S->top];
        cout<<x<<endl;
    return true;
}
int main()
{
    int m,x;
    SeqStack *S;
    createStack(S);    //初始化
    Full_SeqStack(S);  //判满
             //判空
   // InitSert_SeqStack (S);   //入栈
    cout<<"请输入10个元素"<<endl;
    for(int i=0;i<MaxSize;i++)
    {
        int temp_x;
        cin>>temp_x;
        InitSert_SeqStack (S,temp_x);  //入栈
    }
    m=Empty(S);
    cout<<"栈顶元素为:";
    GetTop(S,x);
    if(m==1) cout<<"栈为空"<<endl;
    else cout<<"栈不为空"<<endl;
    cout<<"栈内元素:"<<endl;
    pop(S,x);
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_41542894/article/details/80818821