• Leetcode: 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 top, peek/pop from top, size, 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).

    Lintcode: http://www.cnblogs.com/EdwardLiu/p/4278333.html

     1 class MyQueue {
     2     // Push element x to the back of queue.
     3     LinkedList<Integer> stack1;
     4     LinkedList<Integer> stack2;
     5     
     6     public MyQueue() {
     7         this.stack1 = new LinkedList<Integer>();
     8         this.stack2 = new LinkedList<Integer>();
     9     }
    10     
    11     public void push(int x) {
    12         stack1.push(x);
    13     }
    14 
    15     // Removes the element from in front of queue.
    16     public void pop() {
    17         if (!stack2.isEmpty()) {
    18             stack2.pop();
    19             return;
    20         }
    21         while (!stack1.isEmpty()) {
    22             stack2.push(stack1.pop());
    23         }
    24         if (!stack2.isEmpty()) stack2.pop();
    25     }
    26 
    27     // Get the front element.
    28     public int peek() {
    29         if (!stack2.isEmpty()) return stack2.peek();
    30         else while (!stack1.isEmpty()) {
    31             stack2.push(stack1.pop());
    32         }
    33         return stack2.peek();
    34     }
    35 
    36     // Return whether the queue is empty.
    37     public boolean empty() {
    38         return (stack1.isEmpty() && stack2.isEmpty());
    39     }
    40 }
  • 相关阅读:
    Oracle学习系列7
    oracle 体系结构
    数据库设计三大范式
    Oracle学习系列6
    Oracle学习系列5
    Unity3D for Android 纹理压缩支持
    Unity项目UI图片压缩格式(UGUI)
    [Unity3D]关于U3D贴图格式压缩
    unity 联机调试(android ios)
    UGUI 文字效果实现(ShadowGradientOutline)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060191.html
Copyright © 2020-2023  润新知