码迷,mamicode.com
首页 > 其他好文 > 详细

Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks

时间:2017-07-22 00:43:51      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:return   void   span   tac   asn   port   nbsp   question   实现   

题目原文:

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

标签:return   void   span   tac   asn   port   nbsp   question   实现   

原文地址:http://www.cnblogs.com/evasean/p/7220077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!