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 }
  • 相关阅读:
    获取表信息(MSSQL)
    合并有数据的列
    isnull的使用方法
    查询SQLServer的启动时间
    查询数据库中有数据的表
    查询数据库中表使用的空间信息。
    SQL Server SA 密码丢失无法连接数据库怎么办?
    tensorflow 语法及 api 使用细节
    Python: PS 滤镜-- Fish lens
    中英文对照 —— 概念的图解
  • 原文地址:https://www.cnblogs.com/evasean/p/7220077.html
Copyright © 2011-2022 走看看