Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks
Posted evasean
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks相关的知识,希望对你有一定的参考价值。
题目原文:
Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.
题目要求用栈实现队列的所有操作。
1 import java.util.Iterator; 2 import edu.princeton.cs.algs4.Stack; 3 public class QueueWith2Stacks<Item>{ 4 Stack<Item> inStack = new Stack<Item>(); 5 Stack<Item> outStack = new Stack<Item>(); 6 public boolean isEmpty(){ 7 if(inStack.isEmpty() && outStack.isEmpty()) 8 return true; 9 else return false; 10 } 11 public int size(){ 12 return (inStack.size() + outStack.size()); 13 } 14 public void enqueue(Item item){ 15 inStack.push(item); 16 } 17 public Item dequeue(){ 18 if(outStack.isEmpty()){ 19 if(inStack.isEmpty()) return null; 20 else{ 21 Iterator<Item> sIter = inStack.iterator(); 22 while(sIter.hasNext()){ 23 outStack.push(sIter.next()); 24 } 25 return outStack.pop(); 26 } 27 }else{ 28 return outStack.pop(); 29 } 30 } 31 }
以上是关于Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks的主要内容,如果未能解决你的问题,请参考以下文章
Coursera Algorithms week2 基础排序 Interview Questions: 1 Intersection of two sets
Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks
Coursera TensorFlow 基础课程-week2
Coursera TensorFlow 基础课程-week2