首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。