• 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 }
  • 相关阅读:
    CodeForces 375D. Tree and Queries【树上启发式合并】
    JavaWeb(一)-Servlet知识
    XML解析
    XML约束
    XML
    什么是JWT
    Springboot @ConditionalOnProperty注解
    带你了解HTTP协议(二)
    带你了解HTTP协议(一)
    JAVA十大经典排序算法最强总结(含JAVA代码实现)
  • 原文地址:https://www.cnblogs.com/panini/p/6482241.html
Copyright © 2020-2023  润新知