栈的基本实现c++

    科技2022-09-08  122

    //顺序栈的基本操作 #include<iostream> #define MaxSize 50 typedef int ElemType; //定义栈结构体 typedef struct { ElemType data[MaxSize]; int top; }SqStack; //初始化栈 void InitStack(SqStack &S) { S.top = -1; } //判断栈是否为空 bool StackEmpty(SqStack S) { if(S.top == -1) return true; //栈为空 else return false; } //入栈 bool Push(SqStack &S,ElemType x) { if(S.top == MaxSize-1) return false; S.data[++S.top] = x; return true; } //出栈 bool Pop(SqStack &S,ElemType x) { if(S.top == -1) return false; x = S.data[S.top--]; printf("%d\n",x); //为查看栈的出栈元素 return true; } //获取栈顶元素 bool GetTop(SqStack S,ElemType &x) { if(S.top == -1) return false; x = S.data[S.top]; printf("%d\n",x); //为查看栈的栈顶元素 return true; } int main() { SqStack s;//定义栈 int m,x; InitStack(s);//初始化 Push(s,3);//压入栈 Push(s,9); Push(s,17); Push(s,61); Push(s,278); Push(s,4687); Push(s,6785); Push(s,768); Push(s,45); while(!StackEmpty(s))//如果不为空 { Pop(s,x);//出栈 } return 0; }
    Processed: 0.009, SQL: 10