LeetCode---Implement Queue using Stacks

来源:互联网 发布:java开发erp系统难不难 编辑:程序博客网 时间:2024/05/18 21:40

题目大意:用栈实现队列,包括入队列,出队列,取队头,判空等方法。

算法思想:

1.用两个栈模拟队列,一个栈s1模拟队列的尾部,一个栈s2模拟队列的头部。

2.当入队列是,只需将元素压入s1即可。若s1和s2都为空则队列为空。

3.当出队列时,先判断队列是否为空,若不空则看s2是否为空,不空则去栈顶元素即可,若空则将s1中的元素都压入s2栈中,然后取s2的栈顶元素。

4.同理3可实现队列的出队列操作。

代码如下:

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


0 0
原创粉丝点击