Implement Queue by Two Stacks

原创 2016年05月31日 01:18:54

基础知识的考察,补课

public class Queue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public Queue() {
       // do initialization if necessary
       stack1 = new Stack<>();
       stack2 = new Stack<>();
    }
    
    public void push(int element) {
        // write your code here
        stack2.push(element);
    }

    public int pop() {
        // write your code here
        if (stack1.isEmpty()) {
            stack2ToStack1();
        }
        return stack1.pop();
    }

    public int top() {
        // write your code here
        if (stack1.isEmpty()) {
            stack2ToStack1();
        }
        return stack1.peek();
    }
    
    private void stack2ToStack1() {
        while (!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

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个字)