首页 > 代码库 > 利用两个栈模拟队列

利用两个栈模拟队列

/**************************************************
题目:用两个栈模拟队列的基本操作1入队2,出队3判断队空4判断队满
s1做为输入栈的元素,一个个压栈相当于入队 s2作为输出队列的元素, 一个个出栈相当于出队
*************************************************/
#include <iostream>
#include <cstdio>
using namespace std;
const int maxsize = 1000;
typedef struct sqstack {
    int data[maxsize];
    int top;
}sqstack;
void InitStack(sqstack &s) {
    s.top = -1;
}
bool StackEmpty(sqstack s) {
    if(s.top == -1) return true;
    else return false;
}
bool StackFull(sqstack s) {
    if(s.top == maxsize-1) return true;
    else return false;
}
bool Push(sqstack &s, int x) {
    if(s.top == maxsize-1) return false;
    s.data[++s.top] = x;
    return true;
}
bool Pop(sqstack &s, int &x) {
    if(s.top == -1) return false;
    x = s.data[s.top--];
    return true;
}
bool GetTop(sqstack s, int &x) {
    if(s.top == -1) return false;
    x = s.data[s.top];
    return true;
}

bool Enqueue(sqstack &s1, sqstack  &s2, int x) { // input
    int y;
    if(s1.top == maxsize-1) {          // s1 is full
        if(!StackEmpty(s2)) return false; // and s2 is not  empty.
        else if(StackEmpty(s2)) {          //s2 is empty.
            while(!StackEmpty(s1)) {
                Pop(s1, y);
                Push(s2, y);
            }
            Push(s1, x);
            return true;
        }
    }
    else {
        Push(s1, x);
        return true;
    }
}
bool Dequeue(sqstack &s1, sqstack &s2, int &x) {// output from queue.
    int y;
    if(!StackEmpty(s2)) { // s2 not empty
        Pop(s2, x);
        return true;
    }
    else  {
        if(StackEmpty(s1)) return false; // s1 is empty
        else {
            while(!StackEmpty(s1)){
                Pop(s1, y);
                Push(s2, y);
            }
            Pop(s2, x);
            return true;
        }
    }
}
bool QueueEmpty(sqstack s1, sqstack s2) {
    if(StackEmpty(s1) && StackEmpty(s2))return true;  // queue is empty.
    else return false;
}
bool QueueFull(sqstack s1, sqstack s2){
    if(!StackEmpty(s2) && StackFull(s1)) return true; // queue is full.
    else return false;
}

int main()
{
    sqstack s1, s2;
    int var;
    InitStack(s1); InitStack(s2);
    for(int i = 0; i < 10; i++) {
        Enqueue(s1, s2, i);
    }
    while(!QueueEmpty(s1, s2)) {
        Dequeue(s1, s2, var);
        cout << var << endl;
    }
    return 0;

}

利用两个栈模拟队列