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  */
  • 相关阅读:
    POJ2960 S-Nim
    HDU1850 Being a Good Boy in Spring Festival
    描述性统计-1
    基础-1
    .Net程序调试
    家装设计
    ACDSee技巧
    Timeline Maker 用法小结
    Windows 7 操作系统核心文件
    艺术字的操作
  • 原文地址:https://www.cnblogs.com/zhangboy/p/6558385.html
Copyright © 2011-2022 走看看