栈的基本操作(入栈、出栈)

C++实现入栈、出栈、读栈顶元素、置空栈以及判断栈空否。供参考。


#include<iostream>
#include<stdlib.h>
#define MaxSize 100   //假定预分配的栈空间最多能存放100个表目

using namespace std;

typedef char datatype;     //表面类型为字符
typedef struct{
        datatype s[MaxSize];
        int top;       //栈顶指针 top=-1 即为空栈 
}seqStack;
seqStack st;
datatype x;

using namespace std;

void stack_push(seqStack &st,datatype x);
void stack_pop(seqStack &st,datatype &x);
datatype stack_gettop(seqStack &st);
void stack_clear(seqStack &st);
int stack_empty(seqStack &st);

int main()
{
    st.top=-1; //栈顶赋初值; 
    stack_push(st,'a');
    stack_push(st,'b');
    cout<<stack_gettop(st)<<endl;
    stack_pop(st,x);
    stack_push(st,'c');
    cout<<stack_gettop(st)<<endl;
    
    for(int i=st.top;i>0;i--)
        cout<<st.s[i];
        cout<<endl;
        
    stack_push(st,'d');
    for(int i=0;i<=st.top;i++)
       {
            cout<<i;
            cout<<st.s[i];
       }
    cout<<endl;
    
    system("pause");
    return 0;
} 

void stack_push(seqStack &st,datatype x)
{
    if(st.top>=MaxSize-1)
          cout<<"overflow"<<endl;       //overflow
    else 
         st.s[++st.top]=x;    //push
}

void stack_pop(seqStack &st,datatype &x)
{
    if(st.top==-1)
         cout<<"underflow"<<endl;     //空栈 
    else
        x=st.s[st.top--];
} 

datatype stack_gettop(seqStack &st)
{
     if(st.top==-1)
           cout<<"error"<<endl;
     else 
          return st.s[st.top];          
}

void stack_clear(seqStack &st)
{
     st.top=-1; 
} 

int stack_empty(seqStack &st)
{
    if(st.top==-1)
         return 1;
    else 
         return 0;
}



  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值