zoukankan      html  css  js  c++  java
  • 利用栈Stack实现队列(Queue)

    实现说明:

    入队时,将元素压入s1;

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

    这个思路,避免了重复“倒”栈,仅在须要时才“倒”一次。


    package com.knowledgeStudy.threadLocal;
    
    import java.util.Stack;
    
    public class MyQueue {
    
        Stack<Object> s1 = new Stack<Object>();//入栈
    
        Stack<Object> s2 = new Stack<Object>();//出栈
    
        // Push element x to the back of queue.
        public void push(Object x) {
            s1.push(x);
        }
    
        // Removes the element from in front of queue.  
        public void pop() {
            if (!s2.isEmpty()) {
                s2.pop();
            } else {
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
                s2.pop();
            }
        }
    
        // Get the front element.  
        public Object peek() {
            if (!s2.isEmpty()) {
                return s2.peek();
            } else {
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
                return s2.peek();
            }
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return s1.empty() && s2.empty();
        }
       //測试
        public static void main(String[] args) {
            MyQueue queue = new MyQueue();
            queue.push(1);
            queue.pop();
            System.out.println(queue.empty());
        }
    }
    


  • 相关阅读:
    数据库事务的四大特性以及事务的隔离级别
    informer使用示例
    Linux内存、Swap、Cache、Buffer详细解析
    浏览器访问百度的整个过程
    安装zookeeper
    配置java环境
    promethues开发
    go mod常用操作说明
    redis使用基础
    channel的声明和使用
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7002296.html
Copyright © 2011-2022 走看看