• Implement Queue using Stacks 解答


    Question

    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).

    Solution

    enQueue(q,  x)
      1) Push x to stack1 (assuming size of stacks is unlimited).
    
    deQueue(q)
      1) If both stacks are empty then error.
      2) If stack2 is empty
           While stack1 is not empty, push everything from satck1 to stack2.
      3) Pop the element from stack2 and return it.

    Check each element i, i can only be pushed/ poped once at stack 1, and pushed/ poped once at stack 2. So add(), remove(), peek() still cost O(1) time.

     1 public class Queue {
     2     private Stack<Integer> stack1;
     3     private Stack<Integer> stack2;
     4 
     5     public Queue() {
     6        stack1 = new Stack<Integer>();
     7        stack2 = new Stack<Integer>();
     8     }
     9     
    10     public void push(int element) {
    11         stack1.push(element);
    12     }
    13 
    14     public int pop() {
    15         if (stack1.isEmpty() && stack2.isEmpty())
    16             return 0;
    17         if (stack2.isEmpty()) {
    18             while (!stack1.isEmpty())
    19                 stack2.push(stack1.pop());
    20         }
    21         return stack2.pop();
    22     }
    23 
    24     public int top() {
    25         if (stack1.isEmpty() && stack2.isEmpty())
    26             return 0;
    27         if (stack2.isEmpty()) {
    28             while (!stack1.isEmpty())
    29                 stack2.push(stack1.pop());
    30         }
    31         return stack2.peek();
    32     }
    33 }
  • 相关阅读:
    idea 代码提交到gitee
    flink+nacos实现参数化配置
    循环依赖的学习
    protobuf学习
    idea重置试用期插件
    Idea git 指定回滚版本
    Tomcat8下的Redis会话共享
    建造者设计模式
    Servlet中跨域问题详解
    gRPC
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4862802.html
Copyright © 2020-2023  润新知