zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks

    题目:

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.

    Notes:

      • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
      • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
      • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    链接: http://leetcode.com/problems/implement-queue-using-stacks/

    2/28/2017

     1 public class MyQueue {
     2     Stack<Integer> s;
     3     Stack<Integer> t;    
     4     /** Initialize your data structure here. */
     5     public MyQueue() {
     6         s = new Stack<Integer>();
     7         t = new Stack<Integer>();    
     8     }
     9     
    10     /** Push element x to the back of queue. */
    11     public void push(int x) {
    12         if (s.isEmpty()) s.push(x);
    13         else {
    14             while (!s.isEmpty()) {
    15                 t.push(s.pop());
    16             }
    17             s.push(x);
    18             while (!t.isEmpty()) {
    19                 s.push(t.pop());
    20             }
    21         }        
    22     }
    23     
    24     /** Removes the element from in front of queue and returns that element. */
    25     public int pop() {
    26         return s.pop();        
    27     }
    28     
    29     /** Get the front element. */
    30     public int peek() {
    31         return s.peek();        
    32     }
    33     
    34     /** Returns whether the queue is empty. */
    35     public boolean empty() {
    36        return s.isEmpty();        
    37     }
    38 }
  • 相关阅读:
    8月工作杂记
    好用的MarkDown编辑器
    Windows下遍历某目录下的文件
    Visual Assist 试用期过期怎么办?
    网易有道面试
    Windows操作系统C盘占用空间过多
    如果有一天我当了面试官
    matlab进行三维重建
    HBase , Doris
    《Java程序设计》第6周学习总结
  • 原文地址:https://www.cnblogs.com/panini/p/6482241.html
Copyright © 2011-2022 走看看