首页 > 代码库 > Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks

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