使用两个Stack类(JDK容器类库中的Stack类)实现一个队列类MyQueue,提供队列的入队列和出队列操作:enQueue和deQueue
2013-10-20 13:30
781 查看
使用两个Stack类(JDK容器类库中的Stack类)实现一个队列类MyQueue,提供队列的入队列和出队列操作:enQueue和deQueue;
import java.util.*; public class MyQueue<E> { static Stack st1=new Stack(); static Stack st2=new Stack(); @SuppressWarnings("unchecked") void enQueue(E num) { st1.push(num); } @SuppressWarnings("unchecked") E deQueue() { st1tost2(); E temp=(E) st2.pop(); st2tost1(); return temp; } @SuppressWarnings("unchecked") void st1tost2()//将st1倒入st2; { st2.clear(); while(st1.isEmpty()!=true) { E temp=(E) st1.pop(); st2.push(temp); } } @SuppressWarnings("unchecked") void st2tost1() { st1.clear(); while(st2.isEmpty()!=true) { E temp=(E) st2.pop(); st1.push(temp); } } boolean isEmpty() { if(st1.size()==0) return true; else return false; } public static void main(String[] args) { System.out.print("------------init----------------\nPlease input the queue`s size:"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); MyQueue<Integer> mq=new MyQueue<Integer>(); for(int i=0;i<n;i++) { System.out.print("Please input the "+(i+1)+"number:"); int num=sc.nextInt(); mq.enQueue(num); } System.out.println("-----------insert---------------\nPleas input the number you want to insert:"); while(sc.hasNext()) { int num=sc.nextInt(); mq.enQueue(num); } System.out.println("-----------output------------"); int number=0; while(mq.isEmpty()!=true)//输出全部的元素;(当然也可以一个一个输出) { int it=mq.deQueue(); System.out.println("The "+(number+1)+"th number is:"+it); number++; } } }
相关文章推荐
- 【转】面试题:实现一个队列,这个队列除了有EnQueue, DeQueue操作,还有一个Max操作,三个操作复杂度都是O(1)
- 【数据结构与算法C】利用两个栈S1S2模拟一个队列,用栈的基本操作实线EnQueue,DeQueue,QueueEmpty
- 使用两个栈(stack)实现一个队列(queue)
- 使用堆栈(Stack)来模拟队列(FIFO)功能,要求数据必须存储在堆栈内部.需要实现enqueue(入栈),dequeue(出栈),isEmpty(判空)三个功能,并给出单元测试.
- 实现一个队列,这个队列除了有EnQueue, DeQueue操作,还有一个Max操作,三个操作复杂度都是O(1)
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 使用两个队列实现一个栈
- 剑指offer 7---使用两个栈实现一个队列
- 数据结构与算法分析(Java 语言描述)(36)—— 使用两个队列实现一个栈
- 面试题7_使用两个栈实现一个队列的功能
- JAVA实现用两个栈来实现一个队列,完成队列的Push和Pop操作(《剑指offer》)
- 数据结构 编写一个类,用两个栈实现队列,支持队列的基本操作(add 、poll、peek)
- (试题)使用两个栈实现一个队列
- 算法导论 使用两个队列实现一个栈
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。
- 算法面试题:使用两个堆栈实现一个队列
- 013使用两个栈实现一个队列(keep it up)
- 《剑指Offer》用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。java