zoukankan      html  css  js  c++  java
  • LC.232. Implement Queue using Stacks(use two stacks)

    https://leetcode.com/problems/implement-queue-using-stacks/description/
    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).

    worse case出现在 所有元素都在stack1 中,第一次 从 stack2 中 pop 

    
    
     1 public class LC_232_ImplementQueueUsingStacks {
     2     private Deque<Integer> stack1;
     3     private Deque<Integer> stack2;
     4 
     5     /**
     6      * Initialize your data structure here.
     7      */
     8     public LC_232_ImplementQueueUsingStacks() {
     9         stack1 = new LinkedList<>();
    10         stack2 = new LinkedList<>();
    11     }
    12 
    13     /**
    14      * Push element x to the back of queue.
    15      */
    16     public void push(int x) {
    17         stack1.push(x);
    18     }
    19 
    20     /**
    21      * Removes the element from in front of queue and returns that element.
    22      */
    23     public int pop() {
    24         if (!stack2.isEmpty()) {
    25             return stack2.pop();
    26         } else {
    27             shuffle();
    28             return stack2.pop();
    29         }
    30     }
    31 
    32     /**
    33      * Get the front element.
    34      */
    35     public int peek() {
    36         if (!stack2.isEmpty()) {
    37             return stack2.peek();
    38         } else {
    39             shuffle();
    40             return stack2.peek();
    41         }
    42     }
    43 
    44     private void shuffle() {
    45         while (!stack1.isEmpty()) {
    46             stack2.push(stack1.pop());
    47         }
    48     }
    49 
    50     /**
    51      * Returns whether the queue is empty.
    52      */
    53     public boolean empty() {
    54         return stack1.isEmpty() && stack2.isEmpty();
    55     }
    56 }



  • 相关阅读:
    在visual studio 2010中调用ffmpeg
    RTP/RTCP/RTSP/SIP/SDP
    YV12数据与AVFrame的相互转换
    实现输出h264直播流的rtmp服务器
    RTMP协议发送H.264编码及AAC编码的音视频,实现摄像头直播
    CentOS 硬盘分区方案
    ubuntu默认root密码
    windows下ACE怎样安装与使用说明?
    CentOS 6.4 图文安装教程
    我自己的FFMpeg编译之路
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8598787.html
Copyright © 2011-2022 走看看