zoukankan      html  css  js  c++  java
  • Leecode no.232 栈实现队列

    package leecode;

    import java.util.Stack;

    /**
    * 两个栈实现队列
    * @CreateDate 2021/4/20
    *
    * 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
    */
    public class StackToQueue {
    //标志位 1代表数据在s1,且是正序 2代表数据在s2,且是反序
    Integer flag = 1;
    Stack<Integer> s1 = new Stack();
    Stack<Integer> s2 = new Stack();

    public StackToQueue(){

    }

    /** Push element x to the back of queue. */
    public void push(int x) {
    if(flag == 2){
    while(s2.size() > 0){
    s1.push(s2.pop());
    }
    flag = 1;
    }
    s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
    int r1 = peek();
    int result = s2.pop();
    return result;
    }

    /** Get the front element. */
    public int peek() {
    if(flag == 1){
    while(s1.size() > 0){
    s2.push(s1.pop());
    }
    flag = 2;
    }
    return s2.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
    return flag == 1 ? s1.size() == 0 : s2.size() == 0;
    }

    public static void main(String[] args) {
    StackToQueue stackToQueue = new StackToQueue();
    stackToQueue.push(1);
    stackToQueue.push(2);
    System.out.println(stackToQueue.peek());
    System.out.println( stackToQueue.pop());
    System.out.println(stackToQueue.empty());

    }

    }
  • 相关阅读:
    python多线程实现抓取网页
    调用百度地图实如今地图上定位
    Java创建二叉树
    J2EE的13个规范
    现场故障 案例:控制文件损坏
    数据库原理常见问答
    Lucene整理--中文分词
    Linux发行版
    python中异常好用的工具
    python有趣的一行代码
  • 原文地址:https://www.cnblogs.com/ttaall/p/14680931.html
Copyright © 2011-2022 走看看