問題描述:說明如何用一個數組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>
結果: