题解 | #用两个栈实现队列#

用两个栈实现队列

http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

import java.util.Stack;

/**
 * push 先从第二个栈倒转过来,然后push, 然后再倒转到第二个栈。
 * pop 直接从第二个栈获取数据。
 */
public class TwoStackQueueTest {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.clear();
        while (stack2.size() > 0) {
            stack1.push(stack2.pop());
        }
        stack1.push(node);
        stack2.clear();
        while (stack1.size() > 0) {
            stack2.push(stack1.pop());
        }
    }

    public int pop() {
        return stack2.pop();
    }

    public static void main(String[] args) {
        TwoStackQueueTest test = new TwoStackQueueTest();
        test.push(1);
        test.push(2);
        System.out.println(test.pop());
        System.out.println(test.pop());
    }
}
算法 文章被收录于专栏

数据结构和算法

全部评论

相关推荐

03-16 11:07
南开大学 Java
牛马人的牛马人生:快手卡实习经历的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务