Implement Queue using Stacks

原创 2015年07月08日 14:41:12

解决问题的思路:用两个栈,其中一个栈只是用来作缓存,每次操作结束都为空栈。

代码如下:

class Queue {
private:
    stack<int> stack1;
    stack<int> buf;
public:
    // Push element x to the back of queue.
    void push(int x) {
        for(; !stack1.empty(); ) {
            buf.push(stack1.top());
            stack1.pop();
        }
        stack1.push(x);
        for(; !buf.empty(); ) {
            stack1.push(buf.top());
            buf.pop();
        }

    }

    // Removes the element from in front of queue.
    void pop(void) {
        stack1.pop();
    }

    // Get the front element.
    int peek(void) {
        return stack1.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return stack1.empty();
    }
};

相关文章推荐

Implement Queue using Stacks

Implement Queue using Stacks Implement the following operations of a queue using stacks. pus...

Implement Queue using Stacks

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back o...

【leetcode】232. Implement Queue using Stacks

一、题目描述 Implement the following operations of a queue using stacks. push(x) -- Push element x...

LeetCode:Implement Queue using Stacks

LeetCode:Implement Queue using Stacks1、题目: Implement the following operations of a queue using stac...
  • BestZem
  • BestZem
  • 2016年07月16日 22:08
  • 159

LeetCode232 Implement Queue using Stacks Java 题解

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

Implement Queue using Stacks

解题思路:采用两个栈,实现队列,一个用于进栈S1,一个用于出栈和取头元素S2。进栈时必须将S2中元素全部加入S1中,出栈时必须将S1中的元素加入S2中,才可以保证先进先出。判断为空时,S1,S2均为空...
  • J1n5555
  • J1n5555
  • 2015年09月08日 11:05
  • 180

232. Implement Queue using Stacks(C语言版本)(Time Limit Exceeded)

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back...

LeetCode232—Implement Queue using Stacks

LeetCode232: Implement Queue using Stacks

LeetCode Implement Queue using Stacks

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

232. Implement Queue using Stacks

1.Question Implement the following operations of a queue using stacks. push(x) -- Push element x...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Implement Queue using Stacks
举报原因:
原因补充:

(最多只允许输入30个字)