顺序栈 与 倒序输出

本文介绍了一个使用C++实现的简单顺序栈数据结构。通过定义结构体和一系列基本操作(如初始化、判断栈是否为空、判断栈是否已满、元素入栈与出栈等),演示了如何在程序中运用顺序栈解决实际问题。代码示例展示了完整的栈操作流程。

#include<bits/stdc++.h>
using namespace std;
const int StackSize=10;
typedef struct
{
    int data[StackSize];
    int top;
}SeqStack;            //定义顺序栈 

void InitStack(SeqStack *S)
{
    S->top=-1;
}                     //置栈空 

int StackEmpty(SeqStack *S)
{
    return S->top==-1;
}                     //判栈空

int StackFull(SeqStack *S)
{
    return S->top==StackSize-1;
}                     //判栈满

int Push(SeqStack *S,int x)
{
    if(StackFull(S))
    {
        puts("Error:full");
        return false;
    }
    S->data[++S->top]=x;
    return true;
}                     //进栈 

int Pop(SeqStack *S,int x)
{
    if(StackEmpty(S))
    {
        puts("Error:empty");
        return false;
    }
    x=S->data[S->top-1];
    cout<<x<<" ";
    S->top--; 
    return 1;
}                     //退栈

int StackTop(SeqStack *S,int x)
{
    if(StackEmpty(S))
    {
        puts("Error:empty");
        return false;
    }
    x=S->data[S->top];
    return true;    
}                     //取栈顶
 
int main()
{
    SeqStack *S;
    int x;
    InitStack(S);
    for(int i=1;i<=10;i++)
    {
        cin>>x;
        Push(S,x);
    }
    int t=S->data[S->top];
    StackTop(S,t);
    cout<<t<<" ";
    for(int i=1;i<10;i++)
        Pop(S,t);
    return 0;

//Sequence Stack

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值