关闭

#40 Implement Queue by Two Stacks

标签: lintcodestackqueue
77人阅读 评论(0) 收藏 举报
分类:

题目描述:

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;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12606次
    • 积分:2245
    • 等级:
    • 排名:第16835名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档