zoukankan      html  css  js  c++  java
  • Coursera Algorithms week2 栈和队列 练习测验: Queue with two stacks

    题目原文:

    Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.

    题目要求用栈实现队列的所有操作。

     1 package week2;
     2 
     3 import java.util.Stack;
     4 
     5 /**
     6  * Queue with two stacks. Implement a queue with two stacks so that each queue 
     7  * operations takes a constant amortized number of stack operations
     8  * @author yangjingjing
     9  *
    10  */
    11 public class QueueWith2Stacks<E>{
    12     Stack<E> inStack = new Stack<E>();
    13     Stack<E> outStack = new Stack<E>();
    14     public boolean isEmpty(){
    15         if(inStack.isEmpty() && outStack.isEmpty())
    16             return true;
    17         else return false;
    18     }
    19     public int size(){
    20         return (inStack.size() + outStack.size());
    21     }
    22     public void enqueue(E item){
    23         inStack.push(item);
    24     }
    25     public E dequeue(){
    26         if(outStack.isEmpty()){
    27             if(inStack.isEmpty()) return null;
    28             else{
    29                 while(!inStack.isEmpty()) {
    30                     outStack.push(inStack.pop());
    31                 }
    32                 return outStack.pop();
    33             }
    34         }else{
    35             return outStack.pop();
    36         }
    37     }
    38     public static void main(String[] args) {
    39         QueueWith2Stacks<Object> queue = new QueueWith2Stacks<Object>();
    40         queue.enqueue("a");
    41         queue.enqueue("b");
    42         queue.enqueue("c");
    43         System.out.println(queue.dequeue());
    44         queue.enqueue(1);
    45         queue.enqueue(2);
    46         Object o = null;
    47         while((o = queue.dequeue()) != null) {
    48             System.out.println(o);
    49         }
    50     }
    51 }
  • 相关阅读:
    计算机组成原理
    数据结构和算法: 字符串匹配(一) BF/RK
    数据结构和算法: 动态规划-台阶问题
    数据结构和算法: 散列表
    数据结构和算法: 归并排序/快速排序
    数据结构与算法: 冒泡/插入/选择排序
    过渡内容
    Redis 和缓存技术
    2019字节跳动面试时手撕代码题
    Mysql锁机制
  • 原文地址:https://www.cnblogs.com/evasean/p/7220077.html
Copyright © 2011-2022 走看看