zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    SQL 二进制和字符互转
    拒绝了对对象 'sp_OACreate' (数据库 'mssqlsystemresource',架构 'sys')的 EXECUTE 权限。
    SQL SERVER 正则替换
    SQL SERVER 算法执行效率
    webmin 安装
    MySQL5.6 PERFORMANCE_SCHEMA 说明
    flex 属性
    CSS 实现左侧固定,右侧自适应两栏布局的方法
    项目前端知识点
    为data中的某一个对象添加一个属性不起作用——this.$set的正确使用
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4862802.html
Copyright © 2011-2022 走看看