12-共享栈

基本思想:

一个栈总大小是固定的,分别从上下两个方向向中间入栈。


(西交wrong):

#include <iostream>
#include <stdio.h>
const int maxn = 100;
using namespace std;
struct share_stack{
    int bottom,top;
    int st[maxn];
};
struct share_stack sst;

void push(bool sign,int x)        //sign=1代表从上push,sign=0代表从下push
{
    if(sign)                        //此处未考虑栈满的情况
        sst.st[sst.top--] = x;
    else
        sst.st[sst.bottom++] = x;
}
void pop(bool sign)                 //此处未考虑栈空的情况
{
    if(sign)
        sst.top++;
    else
        sst.bottom--;
}
int top(bool sign)
{
    if(sign)
    return sst.st[sst.top+1];
    else
        return sst.st[sst.bottom-1];
}
int main()
{
    sst.bottom = 1;
    sst.top = maxn-1;
    push(1,3);
    push(1,2);
    push(1,1);

    push(0,1);
    push(0,2);
    push(0,3);

    printf("%d\n",top(1));
    printf("%d\n",top(0));
    return 0;
}

(感谢西交wrong学长提供以上题目练习)

猜你喜欢

转载自blog.csdn.net/outer_star/article/details/82054040
今日推荐