zoukankan      html  css  js  c++  java
  • LC.225. Implement Stack using Queues(use one queue)

    https://leetcode.com/problems/implement-stack-using-queues/description/
    Implement the following operations of a stack using queues.

    push(x) -- Push element x onto stack.
    pop() -- Removes the element on top of the stack.
    top() -- Get the top element.
    empty() -- Return whether the stack is empty.
    Notes:
    You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
    Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

     1 public class LC_225_ImplementStackUsingOneQueue {
     2 
     3     private Queue<Integer> queue1;
     4     private int size ;
     5     public LC_225_ImplementStackUsingOneQueue() {
     6         queue1 = new LinkedList<>();
     7     }
     8 
     9     /**
    10      * Push element x onto stack.
    11      */
    12     public void push(int x) {
    13         queue1.offer(x);
    14     }
    15 
    16     /**
    17      * Removes the element on top of the stack and returns that element.
    18      * stack 1 2 3 4  -> pop the 4
    19      * queue 4 3 2 1  converts to 3214
    20      */
    21     public int pop() {
    22         size = queue1.size() ;
    23         for (int i = 0; i < size-1; i++) {
    24             queue1.offer(queue1.poll()) ;
    25         }
    26         return queue1.poll();
    27     }
    28 
    29     /**
    30      * Get the top element.: peek
    31      * stack 1 2 3 4  -> pop the 4
    32      * queue 4 3 2 1  converts to 3214
    33      */
    34     public int top() {
    35         size = queue1.size() ;
    36         for (int i = 0; i < size-1; i++) {
    37             queue1.offer(queue1.poll()) ;
    38         }
    39         int value = queue1.peek() ;
    40         //first get the 4 then offer the 4 so that the original order is maintained.
    41         queue1.offer(queue1.poll());
    42         return value;
    43     }
    44 
    45     /**
    46      * Returns whether the stack is empty.
    47      */
    48     public boolean empty() {
    49         return queue1.isEmpty();
    50     }
    51 }

    重要假设,必须要时刻知道queue 的 size 如果不知道,则做不了。

  • 相关阅读:
    【leetcode】974. Subarray Sums Divisible by K
    【leetcode】976. Largest Perimeter Triangle
    【leetcode】973. K Closest Points to Origin
    listen 70
    科学60秒 (一) :上
    listen 69
    listen 68 Theoretical Physicist Stephen Hawking Dies at 76
    中译英33
    listen 67
    中译英32
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8598892.html
Copyright © 2011-2022 走看看