zoukankan      html  css  js  c++  java
  • java两栈实现一个队列

    思路

    入队时,将元素压入s1。出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。

    public class QueneWithTwoStacks {
        
        private Stack<Integer> stack1;
        private Stack<Integer> stack2;
        
        public QueneWithTwoStacks() {
            stack1 = new Stack<Integer>();
            stack2 = new Stack<Integer>();
        }
        
        public Integer poll() {
            if (stack1.isEmpty() && stack2.isEmpty())
                return null;
            
            Integer re = null;
            if (!stack2.isEmpty()) {
                re = stack2.pop();
            } else {
                while (!stack1.isEmpty()) {
                    re = stack1.pop();
                    stack2.push(re);
                }
                poll();
            }
            return re;
        }
        
        public Integer insert(int o) {
            stack1.push(o);
            return o;
        }
        
        public static void main(String[] args) {
            QueneWithTwoStacks qw = new QueneWithTwoStacks();
            qw.insert(2);
            qw.insert(1);
            qw.insert(3);
            qw.insert(4);
            System.out.println("出栈----" + qw.poll());
            qw.insert(5);
            qw.insert(9);
            System.out.println("出栈----" + qw.poll());
            System.out.println("出栈----" + qw.poll());
        }
    }
  • 相关阅读:
    web项目优化
    mysql 优化笔记
    Java 调用 google 翻译
    Git回滚merge操作
    mybatis 批量插入 返回主键id
    idea tomcat debug 失效
    mysql 常用语句
    xstream 解析xml报文
    activeMQ 讲解及实战
    linux svn apache
  • 原文地址:https://www.cnblogs.com/amos-s/p/6536370.html
Copyright © 2011-2022 走看看