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 }
  • 相关阅读:
    Linux基础知识
    c语言依赖倒转
    ios的认识
    ios数据的基本类型和流程控制
    JavaScript 创建 自定义对象
    《大道至简》读后感
    总结
    字符串转换成整型并求和
    《大道之简》第二章
    SQL Server 2008 数据库自动备份
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4862802.html
Copyright © 2011-2022 走看看