Implementing queue in java

限于喜欢 提交于 2019-12-04 07:08:24

问题


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?


回答1:


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



回答2:


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.

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



回答3:


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). 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. 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.



来源:https://stackoverflow.com/questions/28131350/implementing-queue-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!