zoukankan      html  css  js  c++  java
  • 用队列实现栈

     1 import java.util.ArrayDeque;
     2 import java.util.Queue;
     3 
     4 public class StackByQueue {
     5     private Queue<Integer> inQueue;
     6     private Queue<Integer> outQueue;
     7     private Queue<Integer> tempQueue = null;
     8 
     9     /**
    10      * Initialize your data structure here.
    11      */
    12     public StackByQueue() {
    13         this.inQueue = new ArrayDeque<>();
    14         this.outQueue = new ArrayDeque<>();
    15     }
    16 
    17 
    18     /**
    19      * Push element x onto stack.
    20      */
    21     public void push(int x) {
    22         inQueue.offer(x);
    23         while (!outQueue.isEmpty()) {
    24             inQueue.offer(outQueue.poll());
    25         }
    26         tempQueue = inQueue;
    27         inQueue = outQueue;
    28         outQueue = tempQueue;
    29 
    30     }
    31 
    32     /**
    33      * Removes the element on top of the stack and returns that element.
    34      */
    35     public int pop() {
    36         return outQueue.poll();
    37     }
    38 
    39     /**
    40      * Get the top element.
    41      */
    42     public int top() {
    43         return outQueue.peek();
    44     }
    45 
    46     /**
    47      * Returns whether the stack is empty.
    48      */
    49     public boolean empty() {
    50         return outQueue.isEmpty();
    51     }
    52 
    53 
    54     public static void main(String[] args) {
    55         StackByQueue obj = new StackByQueue();
    56         obj.push(1);
    57         obj.push(2);
    58 
    59         int param_2 = obj.pop();
    60         int param_3 = obj.top();
    61         boolean param_4 = obj.empty();
    62     }
    63 
    64 }
  • 相关阅读:
    javaScript中的find()方法和返回数据的内存指向
    高级函数 filter map reduce 的使用
    for ... in and for ... of 理解
    git 解决冲突问题
    H5内唤醒百度、高德APP
    HTML 5标准中最新引入的template标签介绍
    jquery选择器使用
    ajax封装函数
    常用正则表达式
    JS-----事件、image对象
  • 原文地址:https://www.cnblogs.com/steve-jiang/p/12568571.html
Copyright © 2011-2022 走看看