您的位置:首页 > 运维架构

10.1-2 说明如何用一个数组A[1..n]来实现两个栈,使得两个栈中的元素总数不到n时,两者都不会发生上溢,注意PUSH和POP操作的时间应为O(1)。

2013-03-10 11:00 666 查看
#include "iostream"
#include "string"
using namespace std;

int A[9]={-1,1,2,3,4,5,6,7,8};
int top_s1=0,top_s2=9;

bool PUSH(string s,int x){
if(top_s1+1==top_s2)
return false;
else{
if(s=="s1"){
top_s1++;
A[top_s1]=x;
}
else{
top_s2--;
A[top_s2]=x;
}
return true;
}
}//入栈

int POP(string s){
if(s=="s1"&&top_s1==0||s=="s1"&&top_s2==9)
return -1;
else{
if(s=="s1"){
top_s1--;
return A[top_s1+1];
}
else{
top_s2++;
return A[top_s2-1];
}
}
}//出栈

void main(){
PUSH("s1",12);
PUSH("s2",32);
PUSH("s1",67);
PUSH("s2",24);
PUSH("s1",13);
PUSH("s1",14);
PUSH("s1",15);
PUSH("s1",16);
if(!PUSH("s1",11))
cout<<"堆栈已经满了!!!"<<endl;
for(int i=1;i<9;i++)
cout<<A[i]<<" ";
cout<<endl;
getchar();
getchar();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐