您的位置:首页 > 理论基础 > 数据结构算法

数据结构—数组实现两个栈,不上溢

2015-05-18 10:45 225 查看
问题描述:说明如何用一个数组A[1..n]来实现两个栈,使得两个栈中的元素总数不到n时,两者都不会发生上溢,注意PUSH和POP操作的时间应为O(1)。(算法导论第三版P131)

思路:stack1,stack2的base分别在数组的两端。stack1每次push的时候top + 1,stack2每次push时top-1,初始时top1=base1,top2=base2,判断是否用空余空间可以用stack1.top > stack2.top。pop操作相反,判断栈空可以用stack.base
== stack.top。

<span style="font-size:18px;">#include <iostream>
#include <string>
using namespace std;
int Array[10]={0};   //假设0表示当前位置中没有数据
int top_s1=0,top_s2=9;
//入栈,top_s1,top_s2表示当前要插入的位置
bool Push(string s,int num)
{
if(top_s1>top_s2)
{
cout<<"栈满!";
exit(0);
}
if (s=="first")
Array[top_s1++]=num;
else
Array[top_s2--]=num;
return true;
}
int Pop(string s)
{
if ((s=="first" && top_s1==0) || (s=="last" && top_s2==9))
{
cout<<"栈空!";
exit(0);
}
if(s=="first")
{
int tmp=Array[--top_s1];
Array[top_s1]=0;
return tmp;
}
else
{
int tmp=Array[++top_s2];
Array[top_s2]=0;
return tmp;
}
}
void main()
{
cout<<"初始为空(0表示当前位置中没有数据):";
for(int i=0;i<10;i++)
cout<<Array[i]<<",";
cout<<endl;
Push("first",20);
Push("first",21);
Push("first",22);
Push("first",23);
Push("last",29);
Push("last",28);
Push("last",27);
Push("last",26);
cout<<"入栈后:";
for(int i=0;i<10;i++)
cout<<Array[i]<<",";
cout<<endl;
Pop("first");
Pop("first");
Pop("last");
cout<<"出栈后:";
for(int i=0;i<10;i++)
cout<<Array[i]<<",";
cout<<endl;
}</span>


结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: