Coursera Algorithms week2 栈和队列 练习测验: Queue with two stacks

本文介绍了一种使用两个栈来实现队列的方法,确保每个队列操作都能在常数级的摊销时间内完成。通过巧妙地在两个栈之间转移元素,实现了队列的基本功能:入队、出队等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原文:

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 }

 

转载于:https://www.cnblogs.com/evasean/p/7220077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值