zoukankan      html  css  js  c++  java
  • Two Stacks Implements A Deque

     1 public class DequeStructure {
     2     Deque<Integer> stack1;
     3     Deque<Integer> stack2;
     4     public DequeStructure () {
     5         stack1 = new LinkedList<>();
     6         stack2 = new LinkedList<>();    
     7     }
     8     
     9     public void leftPush(int x) {
    10         stack1.push(x);
    11     }
    12     
    13     public void rightPush(int x) {
    14         stack2.push(x);
    15     }
    16     
    17     public int leftPop() {
    18         if (stack1.isEmpty() && stack2.isEmpty()) {
    19             return -1;
    20         }
    21         if (stack1.isEmpty()){
    22             shuffle();
    23         }
    24         return stack1.pop();
    25     }
    26     
    27     public int rightPop() {
    28         if (stack1.isEmpty() && stack2.isEmpty()) {
    29             return -1;
    30         }
    31         if (stack2.isEmpty()) {
    32             shuffle();
    33         }
    34         return stack2.pop();
    35     }
    36     
    37     // O(n) operations, very expensive!!
    38     private void shuffle() {
    39         if (stack1.isEmpty()) {
    40             while (!stack2.isEmpty()) {
    41                 stack1.push(stack2.pop());
    42             }
    43         } else {
    44             while (!stack1.isEmpty()) {
    45                 stack2.push(stack1.pop());
    46             }
    47         }
    48     }
    49 }
  • 相关阅读:
    Network UVA
    The Unique MST POJ
    Borg Maze POJ
    javabean,pojo,vo,dto,
    core data,
    iOS block的用法
    写给程序员:我们这一代不是汽车工人
    编译器是如何工作的?
    SQLite可视化管理工具汇总
    NSFetchedResultsController
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8606854.html
Copyright © 2011-2022 走看看