6

JZ-005-用两个栈实现队列

 2 years ago
source link: https://segmentfault.com/a/1190000040858362
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JZ-005-用两个栈实现队列

发布于 10 月 25 日

用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

题目链接: 用两个栈实现队列

import java.util.Stack;

/**
 * 标题:
 * 题目描述
 * 
 * 题目链接
 * 
 */
public class Jz05 {

    // 入队列栈
    Stack<Integer> stack1 = new Stack<Integer>();
    // 出队列栈
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if (stack2.size() == 0 && stack1.size() == 0) {
            throw new RuntimeException("该队列为空");
        }
        if (stack2.size() == 0) {
            while (stack1.size() > 0) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

【每日寄语】 所有看起来的幸运,都源自坚持不懈的努力。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK