简体   繁体   English

用Java实现队列

[英]Implementing queue in java

Implementing a queue in Java is pretty common interview question. 用Java实现队列是相当普遍的面试问题。 I surfed online and saw many implementations where they do fancy stuff like implementing queue interface and writing own addLast() and removeFirst() methods. 我在网上冲浪,看到了许多实现的地方,例如实现队列接口以及编写自己的addLast()removeFirst()方法。 My question is can't I just use LinkedList() class and use its predefined methods addLast and removeFirst methods to do the same?? 我的问题是我不能只使用LinkedList()类并使用其预定义的方法addLastremoveFirst方法来执行相同的操作吗? eg 例如

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();
}
}

I have very recently gone through these kind of interview questions. 最近,我经历了这类面试问题。

Using set methods to add,remove, chekForEmpty etc from a list is a general way to implement a queue. 使用set方法从列表中添加,删除,chekForEmpty等是实现队列的一般方法。

for example : 例如 :

   public void enqueue(E item) {
     list.addLast(item);
     }

   public E dequeue() {
      return list.poll();
      }

   public boolean hasItems() {
      return !list.isEmpty();
      }

   public int size() {
      return list.size();
      }

   public void addItems(GenQueue<? extends E> l) {
      while (l.hasItems())
        list.addLast(l.dequeue());
        }

One way is to maintain an array of items q and two indices to the head and the tail of the queue (initially set to 0). 一种方法是维护项目q的数组以及队列开头和q两个索引(最初设置为0)。 Pseudo-code follows: 伪代码如下:

enqueue(x)
{   q[tail++] = x;
}

dequeue()
{   return q[head++];
}

If the array overflows, you double the size and reinsert the items. 如果数组溢出,则将大小加倍并重新插入项目。 This yields O(1) amortized time per operation. 每次操作产生O(1)摊销时间。 Another approach is to use a linked list (which you should implement) and again store a pointer to the head and a pointer to the tail. 另一种方法是使用一个链表(您应该实现),然后再次存储一个指向头部的指针和一个指向尾部的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM