zoukankan      html  css  js  c++  java
  • 【LeetCode232】 Implement Queue using Stacks★

    1.题目描述

    2.思路

      思路简单,这里用一个图来举例说明:

    3.java代码

     1 public class MyQueue {
     2 
     3    Stack<Integer> stack1=new Stack<Integer>();
     4     Stack<Integer> stack2=new Stack<Integer>();
     5     
     6     /** Push element x to the back of queue. */
     7     public void push(int x) {
     8         stack1.push(x);
     9     }
    10     
    11     /** Removes the element from in front of queue and returns that element. */
    12     public int pop() {
    13         if(!stack2.isEmpty())
    14             return stack2.pop();
    15         else{
    16             while(!stack1.empty())
    17                 stack2.push(stack1.pop());
    18             return stack2.pop();
    19         }
    20     }
    21     
    22     /** Get the front element. */
    23     public int peek() {
    24         if(!stack2.isEmpty())
    25             return stack2.peek();
    26         else{
    27             while(!stack1.empty())
    28                 stack2.push(stack1.pop());
    29             return stack2.peek();
    30         }
    31     }
    32     
    33     /** Returns whether the queue is empty. */
    34     public boolean empty() {
    35         return stack1.empty()&&stack2.empty();
    36     }
    37 }
    38 
    39 /**
    40  * Your MyQueue object will be instantiated and called as such:
    41  * MyQueue obj = new MyQueue();
    42  * obj.push(x);
    43  * int param_2 = obj.pop();
    44  * int param_3 = obj.peek();
    45  * boolean param_4 = obj.empty();
    46  */
  • 相关阅读:
    假丶依赖注入
    .NET Core 傻瓜式CSRedisCore缓存
    .NET Core MD5加密 32位和16位
    数据库所对应的函数
    使用通配符进行过滤
    WHERE 子句操作符
    不同的数据库查询行数的方式
    第一课了解SQL
    微服务架构综述
    三层应用与单块架构
  • 原文地址:https://www.cnblogs.com/zhangboy/p/6558385.html
Copyright © 2011-2022 走看看