7-4 堆栈模拟队列 (25 分)
7-4 堆棧模擬隊列 (25 分)
設已知有兩個堆棧S1和S2,請用這兩個堆棧模擬出一個隊列Q。
所謂用堆棧模擬隊列,實際上就是通過調用堆棧的下列操作函數:
int IsFull(Stack S):判斷堆棧S是否已滿,返回1或0;
int IsEmpty (Stack S ):判斷堆棧S是否為空,返回1或0;
void Push(Stack S, ElementType item ):將元素item壓入堆棧S;
ElementType Pop(Stack S ):刪除并返回S的棧頂元素。
實現隊列的操作,即入隊void AddQ(ElementType item)和出隊ElementType DeleteQ()。
輸入格式:
輸入首先給出兩個正整數N1和N2,表示堆棧S1和S2的最大容量。隨后給出一系列的隊列操作:A item表示將item入列(這里假設item為整型數字);D表示出隊操作;T表示輸入結束。
輸出格式:
對輸入中的每個D操作,輸出相應出隊的數字,或者錯誤信息ERROR:Empty。如果入隊操作無法執行,也需要輸出ERROR:Full。每個輸出占1行。
輸入樣例:
3 2 A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
輸出樣例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
這道題我一開始用的stl,后來遇到重題了,就用數組模擬了一遍,發現用stl真的是很簡單。下面分別附上stl和非stl的方法。
//stl實現 #include <bits/stdc++.h> using namespace std; int main() {stack<int>s1,s2;int m,n,t;cin>>m>>n;if (n>m){t=m;m=n;n=t;} //s2 smallerchar c;int num;getchar();while (1){scanf("%c",&c); //A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D Tif (c=='T'){break;}if (s2.size()==n&&s1.empty()){while(!s2.empty()){s1.push(s2.top());s2.pop();}}if (c=='A'&&s2.size()!=n){scanf("%d ",&num);s2.push(num);}else if (c=='A'&&s2.size()==n){scanf("%d",&num);printf("ERROR:Full\n");}if (c=='D'&&s1.empty()){printf("ERROR:Empty\n");}else if (c=='D'&&!s1.empty()){printf("%d\n",s1.top());s1.pop();}}return 0; }//數組構建棧模擬 #include <bits/stdc++.h> using namespace std; int main() {int n1,n2,top1=-1,top2=-1,t;cin>>n1>>n2; //n2是比較小的if (n2>n1){t=n1;n1=n2;n2=t;}getchar();int s1[100],s2[100]; //3 2char c; //A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D Tint x;scanf("%c",&c);while (c!='T'){if (c=='A'){if(top2<n2-1) //如果短的2沒滿,一直填充到2.{scanf("%d",&x);s2[++top2]=x;getchar();}else if (top2==n2-1&&top1!=-1) //如果2滿了但是1不為空,此時無法進行數據移動,輸出FULL. {scanf("%d",&x);getchar();printf("ERROR:Full\n");}else if (top2==n2-1&&top1==-1) //如果2滿了但是1是空的,數據移動,全部移過去. {while (top2!=-1){s1[++top1]=s2[top2--];}scanf("%d",&x);s2[++top2]=x;getchar();}}if (c=='D'){getchar();if (top1!=-1) //如果1不是空的,先輸出1,因為他的數輸入的更早. {printf("%d\n",s1[top1--]);}else if (top2!=-1&&top1==-1) //如果2不是空的但是1是空的,轉換數據,再輸出. {while (top2!=-1){s1[++top1]=s2[top2--];}printf("%d\n",s1[top1--]);}else if (top1==-1&&top2==-1) //都是空的,輸出錯誤提示. {printf("ERROR:Empty\n");}}scanf("%c",&c);}return 0; }
總結
以上是生活随笔為你收集整理的7-4 堆栈模拟队列 (25 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多线程下实现自增的几种方式
- 下一篇: Leetcode--1248. 统计「优