队列和栈的相互表示

来源:互联网 发布:网络信用卡 编辑:程序博客网 时间:2024/06/01 16:55

用栈表示队列

方法1:
1.用两个栈tmp和S,tmp当做中介。
2.每次有push操作时,先将s中的元素全部倒入tmp中(s若为空则无操作),此时再进行push操作压入新元素。
3.操作完成后再将tmp中所有元素倒入s中,从s中弹出的元素即为队列元素的弹出顺序。
4.pop操作则为s.pop(),empty则为s.empty()。top操作也是取s的top。
方法2(方法1的改进):
1.在方法1pop操作时先判断s是否为空,如果不为空直接进行s.pop(),如果为空,则此时直接将tmp中的元素倒入s中,对s进行pop;
2.取top操作和pop操作类似,判断栈空要看两个栈是否都为空,size操作也一样。
方法一代码

class Queue {public:    stack<int> tmp, s;    // Push element x to the back of queue.    void push(int x) {        while (!s.empty()){            tmp.push(s.top());            s.pop();        }        tmp.push(x);        while (!tmp.empty()){            s.push(tmp.top());            tmp.pop();        }    }    // Removes the element from in front of queue.    void pop(void) {        s.pop();    }    // Get the front element.    int peek(void) {        return s.top();    }    // Return whether the queue is empty.    bool empty(void) {        return s.empty();    }};

用队列表示栈

方法一
1.建立两个队列q和tmp,tmp为中介。
2.push:将q中的元素按出队列顺序倒入tmp中,然后元素压入q中,再将tmp中元素按顺序倒回q中。
3.pop:q.pop()。front:q.front();。empty:q.empty();
方法一代码

class Stack {public:    queue<int> q, tmp;    // Push element x onto stack.    void push(int x) {        while (!q.empty()){            tmp.push(q.front());            q.pop();        }        q.push(x);        while (!tmp.empty()){            q.push(tmp.front());            tmp.pop();        }    }    // Removes the element on top of the stack.    void pop() {        q.pop();    }    // Get the top element.    int top() {        return q.front();    }    // Return whether the stack is empty.    bool empty() {        return  q.empty();    }};
0 0
原创粉丝点击