#include
#include
using namespace std;
template
class CStack
{
public:
CStack(int arg) : elements(arg, 0){
size = arg;
topIndex = -1;
}
~CStack() {
}
void Push(T arg) {
if (topIndex == size - 1)
throw "Overflow";
else
{
topIndex++;
elements[topIndex]=arg;
}
}
T Pop() {
if (topIndex == -1)
throw "Underflow";
else
{
topIndex--;
return elements[++topIndex];
}
}
bool IsEmpty() {
if(topIndex==-1)
return 1;
else
return 0;
}
private:
int size;
int topIndex;
vector elements;
};
template
class CQueueOnStack {
private:
CStack inbox;
CStack outbox;
public:
CQueueOnStack(int arg) : inbox(arg), outbox(arg) {}
void Enqueue (T arg1) {
inbox.Push(arg1);
}
T Dequeue () {
if(outbox.IsEmpty())
{
outbox.Push(inbox.Pop());
return outbox.Pop();
}
else
return outbox.Pop();
}
};
void testCStack() {
CStack stack(3);
try {
stack.Pop();
} catch (const char* e) {
printf("Catch %s exception\n", e);
}
stack.Push(1);
stack.Push(2);
stack.Push(3);
try {
stack.Push(4);
} catch (const char* e) {
printf("Catch %s exception\n", e);
}
while (!stack.IsEmpty())
printf("%d\n", stack.Pop());
}
void testQueueOnStack() {
CQueueOnStack queue(10);
for (int i = 0; i < 5; ++i)
queue.Enqueue(i);
for (i = 0; i < 3; ++i)
printf("%d\n", queue.Dequeue());
queue.Enqueue(5);
queue.Enqueue(6);
for (i = 0; i < 4; ++i)
printf("%d\n", queue.Dequeue());
}
int main() {
testCStack();
testQueueOnStack();
return 0;
}
程序无法正确运行,不知道哪里有问题。