利用java实现队列

叙言.ZXF 2007-11-10 12:36:13
面试题: 利用java代码实现一个简单的队列, 有一个队列类和测试类, 如整数1,2,3,4,5输入队列, 在控制台上打印输入1 2 3 4 5 ?
以下是我面试时写的一段代码, 但我没有实现输入的功能? 请高手指点或给出详细代码.

public class TestQueue {

public static void main(String[] args) {
int[] num={1,2,3,4,5};
Queue q=new Queue();
q.queue(num);
}
}

class Queue{
public void queue(int [] a){
for (int i=0;i<a.length;i++){
if (a!=null){
System.out.print(a[i]+" ");
}
}
}
}
...全文
4067 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
guotiannmg2010 2011-05-24
  • 打赏
  • 举报
回复

package test;
/**
* 队列规则:先进先出
* 插入一端为队尾,
* 删除一端为队头。
* @author GT
*/
public class integerQueue {
int Queuereat ;//队尾
int queueSize;//对长
public static void main(String[] args){
int que[] = {1,2,3,4};
enQueue(que);
}
public boolean queueEmpty(){//判断队列是否为空,空则返回true,否则返回false
if(queueEmpty()){
return true;
}else{
return false;
}
}
public static void enQueue(int q[]){//入队 向队列插入元素
for (int i= 0; i < q.length; i++) {
System.out.println(q[i]);
}
}
public void deQueue(){//出队 从队列删除元素


}
}
我迷茫不知所措!
superliubao 2009-09-28
  • 打赏
  • 举报
回复
学习。。。
peter8015 2009-09-06
  • 打赏
  • 举报
回复
public class TestQueue {
public static void main(String args[]) {
int[] k = {1,2,3,4,5};

getOutput(k);
}

public static void getOutput(int[] k) {
Queue queue = new LinkedList(); //ListedList implements Queue

for(int i = 0; i < k.length; i++) {
queue.offer(String.valueOf(k[i]));

System.out.print(queue.poll());
System.out.print(" ");
}

}

}
叙言.ZXF 2007-11-11
  • 打赏
  • 举报
回复
楼上考虑得比我周到, 我知道队列的特点, 当时就没有考虑到要分别写一个入队和出队方法, 估计我做的不叫队列程序题啦.

是要求整数
入队1,2,3,4,5
出队1 2 3 4 5
kaiserlu 2007-11-11
  • 打赏
  • 举报
回复
实现队列的数据结构一般为:数组或链表
Java中有集合框架来实现,要自己实现的话,只要定义一个类实现Queue接口,并且实现相应的方法即可。
一般需要实现的方法:
E element()
检索,但是不移除此队列的头。
boolean offer(E o)
如果可能,将指定的元素插入此队列。
E peek()
检索,但是不移除此队列的头,如果此队列为空,则返回 null。
E poll()
检索并移除此队列的头,如果此队列为空,则返回 null。
E remove()
检索并移除此队列的头。

对于数组的数据结构,用Object[]数组来存放;
对于链表的数据结构,用内部类class Entry<E>{
E element;
Entry next;
Entry previous;
}来存放;
John_2001_83 2007-11-10
  • 打赏
  • 举报
回复
题目要求在控制台上输入了么?整数队还是其他什么队?
队列的话,是不是应该实现一个进队一个退队方法呢?用进队实现输入,输出中包含退队
以上是我看了你的问题以后的一些问题,可能想法有不对的地方。^^ 下面是我实现的一个类
class IntegerQueue{
public int[] integerQueue;//用来当队列
public int tail;//队尾
public int size;//队的长度,也可以设置一个默认值,溢出时从新申请
public IntegerQueue(int size){
integerQueue=new int[size];
this.size=size;
tail=0;
}
public void inQueue(int i){
if(tail<size){
this.integerQueue[tail]=i
tail++;
}else{
System.err.println("溢出啦!");
}
}
public int outQueue(){
int tmp;
if(tail>=0){
tmp=this.integerQueue[tail];
tail--;
reutrn tmp;
}else{
System.err.println("没东东啦!");
}
}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧