Link: http://pat.zju.edu.cn/contests/ds/3-08
It is known that there are two stacks S1 and S2. Use these two stacks to simulate a queue Q.
The so-called use of stack to simulate a queue is actually to call the following operation functions of the stack:
(1) int isfull (stack S): checks whether the stack S is full and returns 1 or 0;
(2) int isempty (stack S): checks whether the stack S is empty, and returns 1 or 0;
(3) void push (stack S, elementtype item): pushes the element item to stack S;
(4) elementtype POP (stack S): deletes and returns the top element of stack S.
Implement queue operations, that is, entering the void addq (elementtype item) and leaving the elementtype deleteq ().
Input format description:
The input first gives two positive integers N1 and N2, indicating the maximum capacity of stack S1 and S2. Then a series of queue operations are given: "A item" indicates that the item is listed (Here we assume that the item is an integer number); "D" indicates that the queue operation is performed; "T" indicates that the input is completed.
Output format description:
For each "D" Operation in the input, output the corresponding number or error message "error: empty ". If the team entry operation cannot be performed, you also need to output "error: Full ". Each output occupies one row.
Sample input and output:
Serial number |
Input |
Output |
1 |
2 2A 1 A 2 D D T |
12 |
2 |
3 2A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T |
ERROR:Full1ERROR:Full23478ERROR:Empty |
PS:
I personally think the question is a bit difficult to understand! I have understood it for a long time!
The Code is as follows:
# Include <cstdio> # include <cstring> # include <iostream> # include <queue> # include <stack> using namespace STD; stack <int> S1; // stack with small capacity <int> S2; // stack with Large Capacity int main () {int N1, N2; char C; while (~ Scanf ("% d", & N1, & N2) {If (N1> N2) {int T = N1; n1 = n2; N2 = N1 ;} getchar (); int tt; int flag = 0; For (INT I = 0; I ++) {scanf ("% C", & C ); if (C = 'T') // end input break; If (C = 'A') {scanf ("% d", & TT ); if (s1.size () = N1 & s2.size ()! = 0) // if Stack S1 is full and stack S2 is not empty, the team is full {printf ("error: full \ n"); continue;} If (s1.size ()! = N1) // If the stack S1 is not full, press s1.push (TT); else {int Len = s1.size (); // If the stack S1 is full, push all elements of stack S1 to s2for (INT I = 0; I <Len; I ++) {int T = s1.top (); s1.pop (); s2.push (t);} s1.push (TT); // press S1} else if (C = 'D') {If (s1.size () = 0 & s2.size () = 0) {printf ("error: Empty \ n"); continue;} If (s2.size () = 0) // if Stack S2 is empty, all elements in S1 will pop up to stack S2, and then the output stack {int Len = s1.size (); For (INT I = 0; I <Len; I ++) {int T = s1.top (); s1.pop (); s2.push (t) ;}} printf ("% d \ n", s2.top ()); s2.pop () ;}} return 0 ;}
3-08. Stack simulation Queue (25) (zju_pat simulation)