在java中实现队列 [英] Implementing queue in java
本文介绍了在java中实现队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中实现队列是一个非常常见的面试问题。我在线浏览并看到许多实现,他们做了很多花哨的东西,如实现队列接口和编写自己的 addLast()
和 removeFirst()
方法。我的问题是我不能只使用 LinkedList()
类并使用其预定义的方法 addLast
和 removeFirst
方法做同样的事情?
例如。
Implementing a queue in Java is pretty common interview question. I surfed online and saw many implementations where they do fancy stuff like implementing queue interface and writing own addLast()
and removeFirst()
methods. My question is can't I just use LinkedList()
class and use its predefined methods addLast
and removeFirst
methods to do the same??
e.g.
LinkedList<Student> qu=new LinkedList<Student>();
qu.add(new Student("anadkat1"));
qu.add(new Student("anadkat2"));
qu.add(new Student("anadkat5"));
System.err.println(qu);
qu.removeFirst();
System.err.println(qu);
这给了我完美的结果。这还不够吗?
This is giving me the perfect result. Isn't this enough?
推荐答案
public class Queue<T>{
private LinkedList<T> list=new LinkedList<>();
public void insert(T element){
list.addLast(element);
}
public void remove(){
list.removeFirst();
}
public int size(){
return list.size();
}
public T element(){
return list.getFirst();
}
}
这篇关于在java中实现队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文