使用一个数组实现两个堆栈

/*
使用一个数组实现两个堆栈,要求最大的利用数组空间,使数组只要有空间入栈操作就可以 成功

分析:一种比较聪明的方法是使这两个栈分别从数组
两头开始向中间生长,当两个栈的栈顶指针相遇,表示栈满
*/
#include <iostream>
#include <cstdio>
using namespace std;
const int MaxSize = 1e3;
struct Dstack{
    int Data[MaxSize];
    int top1,top2;
} S;

void Push(struct Dstack *Ptrs,int item,int tag){
    if(Ptrs->top2-Ptrs->top1==1){
        printf("堆栈满了
");return;
    }
    if(tag==1)
        Ptrs->Data[++(Ptrs->top1)]=item;
    else
        Ptrs->Data[--(Ptrs->top2)]=item;

}
int pop(struct Dstack *Ptrs,int tag){
    if((tag&&Ptrs->top1==-1)||((!tag)&&Ptrs->top2==MaxSize)){
        printf("栈空
");return NULL;
    }
    if(tag){
        return Ptrs->Data[(Ptrs->top1)--];
    }
    else
        return Ptrs->Data[(Ptrs->top2)++];
}
int main()
{
    int item,flag;
    S.top1=-1;
    S.top2=MaxSize;
    for(int i=0;i<5;i++){
        scanf("%d%d",&item,&flag);
        Push(&S,item,flag);
    }
    for(int i=0;i<5;i++){
        scanf("%d",&flag);
        printf("%d
",pop(&S,flag));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/acmtime/p/5917706.html