栈数组实现 pop push show

栈(stack)是限定仅在表尾进行插入和删除操作的线性表,允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。

栈又称为后进先出(LastIn First Out)的线性表,简称LIFO结构。

栈元素具有线性关系,即前驱后继关系。只不过它是一种特殊的线性表而已。定义中说是在线性表的表尾进行插入和删除操作,这里表尾是指栈顶,而不是栈底。

堆叠数据结构使用两种基本操作:推入(push)和弹出(pop):

  • 推入:将数据放入堆叠的顶端(阵列形式或串列形式),堆叠顶端top指标加一。
  • 弹出:将顶端数据资料输出(回传),堆叠顶端资料减一。

阵列堆叠

堆栈可以用链表数组两种方式实现,一般为一个堆栈预先分配一个大小固定且较合适的空间并非难事,所以较流行的做法是Stack结构下含一个数组。

如果空间实在紧张,也可用链表实现,且去掉表头。这里是以数组实现的。

代码:

//阵列堆叠
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstdbool>
using namespace std;
struct stack
{
    int map[10];//开辟空间
    int top;
};
bool empty(struct stack *s)//判断栈空
{
    return s->top==0;
}
void push(struct stack *s,int x)
{
    s->top=s->top+1;
    s->map[s->top]=x;
}
int pop(struct stack *s,int i)
{
    if(empty(s))
    {
        return 0;
    }
    else
    {
        while(i--)
        {
           s->top=s->top-1;
        }
        return s->map[s->top+1];
    }
}
int show(struct stack *s)
{
    for(int i=1;i<=s->top;i++)
    {
        cout<<s->map[i]<<" ";
    }
    cout<<endl;
    return 0;
}

int main()
{
    stack s;
    s.top=0;//栈顶归零
    cout<<"1:push  2:pop  3:show"<<endl;
    while(1)
    {
        char a;
        cin>>a;
        switch(a)
        {
            case '1':
            {
                cout<<"The number of numbers to insert:";
                int num;
                cin>>num;
                int t;
                for(int i=0;i<num;i++)
                {
                    cin>>t;
                   push(&s,t);
                }
                break;
            }
            case '2':
            {
                cout<<"The number of numbers to be deleted:";
                int num;
                cin>>num;
                pop(&s,num);
                break;
            }
            case '3':
            {
                show(&s);
                break;
            }
        }
    }
    return 0;
}

今天也是元气满满的一天!good luck!

原文地址:https://www.cnblogs.com/cattree/p/7534821.html