#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #define MAXSIZE
The using namespace Std;
struct stack{int s[maxsize];
int top=0;
BOOL StackOverflow () {if (top >= MAXSIZE) return true;
return false;
} bool Push (int x) {if (StackOverflow ()) return false;
s[top++] = x;
} bool IsEmpty () {return top==0? true:false;
} bool Pop (int &x) {if (IsEmpty ()) return false;
x = S[--top];
return true;
} int Size () {return top;
}
};
struct queue{//This implementation is also the most likely to think of the Stack S1, s2;//s1 for the queue of push and pop, S2 for the buffer (the data in the S1 to reverse the order of the queue) bool push (int x) {
if (S1.stackoverflow ()) return false;
int e;
while (!s1.isempty ()) {S1.pop (e);
S2.push (e);
} s1.push (x);
while (!s2.isempty ()) {S2.pop (e);
S1.push (e); } return true;
} bool Pop (int &x) {if (S1.isempty ()) return false;
S1.pop (x);
return true;
} bool IsEmpty () {return s1.size () = = 0? true:false;
} int Size () {return s1.size ();
}
}; struct queue_x{//This way the space utilization is larger some Stack S1, s2;//s1 for the queue of push, S2 for the queue of pop bool push (int x) {if (!s1.stackove
Rflow ()) {S1.push (x);
return true;
} if (S1.stackoverflow () &&!s2.isempty ()) return false;
int e;
while (!s1.isempty ()) {S1.pop (e);
S2.push (e);
} s1.push (x);
return true;
} bool Pop (int &x) {if (!s2.isempty ()) {s2.pop (x);
return true;
} if (S1.isempty ()) return false;
int e;
while (!s1.isempty ()) {S1.pop (e);
S2.push (e);
} s2.pop (x);
return true; } boOl IsEmpty () {return s1.size () = = 0 && s2.size () = = 0;
} int Size () {return s1.size () + s2.size ();
}
};
int main () {Queue q;
for (int i=0; i<10; ++i) Q.push (i);
int x;
for (int i=0; i<10; ++i) {q.pop (x);
cout<<x<<endl;
Q.push (100);
} cout<< "The current size of the queue:" <<q.size () <<endl;
while (!q.isempty ()) {q.pop (x);
cout<<x<<endl;
} cout<< "******************************************************" <<endl;
Queue_x QX;
for (int i=0; i<10; ++i) Qx.push (i);
for (int i=0; i<10; ++i) {qx.pop (x);
cout<<x<<endl;
Qx.push (100);
} cout<< "The current size of the queue:" <<qx.size () <<endl;
while (!qx.isempty ()) {qx.pop (x);
cout<<x<<endl;
} return 0; }