zoukankan      html  css  js  c++  java
  • LeetCode-232 Implement Queue using Stacks Solution (with Java)

    1. Description:

    Notes: 

    2. Examples:

    3.Solutions:

     1 /**
     2  * Created by sheepcore on 2019-03-07
     3  * Your MyQueue object will be instantiated and called as such:
     4  * MyQueue obj = new MyQueue();
     5  * obj.push(x);
     6  * int param_2 = obj.pop();
     7  * int param_3 = obj.peek();
     8  * boolean param_4 = obj.empty();
     9  */
    10 class MyQueue {
    11     /** Initialize your data structure here. */
    12     Stack<Integer> input = new Stack<Integer>();
    13     Stack<Integer> output = new Stack<Integer>();
    14 
    15     /** Push element x to the back of queue. */
    16     public void push(int x) {
    17         input.push(x);
    18     }
    19 
    20     /** Removes the element from in front of queue and returns that element. */
    21     public int pop() {
    22         peek();
    23         return output.pop();
    24     }
    25 
    26     /** Get the front element. */
    27     public int peek() {
    28        if(output.empty()){
    29            while (!input.empty()){
    30                output.push(input.pop());
    31            }
    32        }
    33        return output.peek();
    34     }
    35 
    36     /** Returns whether the queue is empty. */
    37     public boolean empty() {
    38         return input.empty() && output.empty();
    39     }
    40 }
  • 相关阅读:
    CentOS7- 配置阿里镜像源
    MySQL学习笔记
    OSI&TCP/IP模型
    加密算法学习
    golang学习笔记
    Redis学习总结整理
    TCP
    HTTP/HTTPS
    HTTP2
    MVCC
  • 原文地址:https://www.cnblogs.com/sheepcore/p/12395208.html
Copyright © 2011-2022 走看看