zoukankan      html  css  js  c++  java
  • 面试题 9:用两个栈实现队列

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

    思路

    入队列:将元素依次进入Stack1中.

    出队列:如果Stack2是空的,将Stack1中的元素全部移到Stack2中,从Stack2中出队列。如果非空,直接从Stack2中出队列.

    package Chapter2_jichuzhishi;
    
    import java.util.Stack;
    /**
     * @Name:
     * @Description:用两个栈来实现一个队列,完成队列的Push和Pop操作。 
     * 队列中的元素为int类型。
     * @Author: Allen
     */
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.add(node);
        }
        
        public int pop() {
            if(stack1.isEmpty()&&stack2.isEmpty()){
                throw new RuntimeException("Queue is empty");
            }
            if(stack2.isEmpty()){
                while(!stack1.isEmpty()){
                    stack2.add(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
  • 相关阅读:
    zoj-1610线段树刷题
    poj-3268最短路
    poj-2528线段树练习
    线段树-最小逆序数hdu1394
    线段树延迟更新
    hdu-4027线段树练习
    RMQ_第一弹_Sparse Table
    字符串hash与字典树
    背包问题
    网络流
  • 原文地址:https://www.cnblogs.com/Allen-win/p/8093848.html
Copyright © 2011-2022 走看看