• 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 }
  • 相关阅读:
    抓包获得东北大学的课程表,考试成绩
    都四次上课练习
    基于WolframAlphaAPI的科学计算器原型设计
    原型设计工具比较及实践
    Xamarin.Forms实现扫码登陆程序移动端(上)
    Hello World!
    程序员的路
    Angularjs 异步模块加载项目模板
    推荐一个 angular 图像加载插件
    前端,我为什么不要你
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060191.html
Copyright © 2020-2023  润新知