//
// main.cpp
// 两栈共享空间结构
//
// Created by Maggie on 18/8/21.
// Copyright © 2018年 Maggie. All rights reserved.
//
//两栈共享空间结构
#include <iostream>
using namespace std;
typedef int SElemType;
#define MAXSIZE 100
typedef struct
{
SElemType data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
// 插入元素e为新的栈顶元素
int Push(SqDoubleStack* S,SElemType e,int stackNumber){
//栈已满,不能再push新元素了
if (S->top1+1==S->top2)
{
return -1;
}
// 栈1有元素进栈
if(stackNumber==1){
// S->data[top1+1]=e;
// S->top1++;
S->data[++S->top1]=e;
return S->top1;
}
else if(stackNumber==2){
S->data[--S->top2]=e;
return S->top2;
}
return 0;
}
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
int Pop(SqDoubleStack *S,int stackNumber){
int e=0;
if(stackNumber==1){
// 说明栈1已经是空栈,溢出
if(S->top1==-1){
return -1;
}
// 将栈1的栈顶元素出栈
e=S->data[S->top1--];
}
else if(stackNumber==2){
// 说明栈2已经是空栈,溢出
if(S->top2==MAXSIZE){
return -1;
}
// 将栈2的栈顶元素出栈
e=S->data[S->top2++];
}
return e;
}
int main(void){
SqDoubleStack S;
(&S)->top1=-1;
(&S)->top2=MAXSIZE;
int a=Push(&S, 1, 1);
int b=Push(&S, 1, 2);
int c=Pop(&S, 1);
int d=Pop(&S,2);
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
return 0;
}
1,TOP1,TOP2均为SqDoubleStack结构内的熟悉,使用时应是S-> TOP1,S-> TOP2,而不是直接用TOP1,TOP2。
2,栈1为空时,就是TOP1等于-1时;而当TOP2等于Ñ时,即是栈2为空时,那什么时候栈满呢想想极端的情况,若栈2是空栈,栈1的TOP1等于N-1时,就是栈1满了。反之,当栈1为空栈时,TOP2等于0时,为栈2满。但更多的情况,其实是两个栈见面之时,也就是两个指针之间相差1时,即TOP1 + 1 == TOP2为栈满。
3,对于两栈共享空间的推方法,我们除了要插入元素值参数外,还需要有一个判断是栈1还是栈2的栈号参数stackNumber。
如图4所示,使用这样的数据结构,通常都是当两个栈的空间需求有相反关系时,也就是一个栈增长时另一个栈在缩短的情况。就像买卖股票一样,你买入时,一定是有一个你不知道的人在做卖出操作。有人赚钱,就一定是有人赔钱。这样使用两栈共享空间存储方法才有比较大的意义。否则两个栈都在不停地增长,那很快就会因栈满而溢出了。
---------------------
部分摘录来自:程杰“大话数据结构” .iBooks。