您的位置:首页 > 编程语言 > Java开发

使用两个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++;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐