設已知有兩個堆棧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
題目 : 給你兩個有長度限制的棧,去模擬一個隊列
思路分析 : 對於有長度限制的,棧中所能存放的數的個數最多是短的棧的個數的二倍,模擬下就好了
代碼示例 :
#define ll long long
const int maxn = 1e6+5;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
stack<int>a,b;
int cnt = 0;
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n, m, num;
char s[5];
cin >> n >> m;
if (n < m) swap(n, m);
int pt = 0;
while(1){
scanf("%s", s);
if (s[0] == 'T') break;
else if (s[0] == 'A') {
scanf("%d", &num);
if (a.size() == m) {printf("ERROR:Full\n"); continue;}
a.push(num);
}
else {
if (b.empty() && a.empty()) {printf("ERROR:Empty\n"); continue;}
if (!b.empty()) {printf("%d\n", b.top()); b.pop();}
else {
while(!a.empty()){
int v = a.top();
a.pop();
b.push(v);
}
printf("%d\n", b.top());
b.pop();
while(!b.empty()){
int v = b.top();
b.pop();
a.push(v);
}
}
}
if (a.size() == m) {
if (b.empty()) {
while(!a.empty()){
int v = a.top();
a.pop();
b.push(v);
}
}
}
}
return 0;
}
