#40 Implement Queue by Two Stacks

原创 2016年08月29日 04:19:37

题目描述:

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element)pop() and top()where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example
push(1)
pop()     // return 1
push(2)
push(3)
top()     // return 2
pop()     // return 2
Challenge 

implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

Mycode(AC = 37ms):

class Queue {
public:
    stack<int> stack1;
    stack<int> stack2;

    Queue() {
        // do intialization if necessary
    }

    void push(int element) {
        // write your code here
        stack1.push(element);
    }
    
    int pop() {
        // write your code here
        while (!stack1.empty()) {
            stack2.push(stack1.top());
            stack1.pop();
        }
        
        int val = stack2.top();
        stack2.pop();
        while(!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        
        return val;
    }

    int top() {
        // write your code here
        while (!stack1.empty()) {
            stack2.push(stack1.top());
            stack1.pop();
        }
        
        int val = stack2.top();
        while(!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        
        return val;
    }
};


版权声明:三千微尘里,吾宁爱与憎

相关文章推荐

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...

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均为空...

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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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