I wanted to know what changes should I be making to this code to reduce its execution time.
import java.util.*;
public class ExamPeekableQueueImpl <E extends Comparable<E>> implements ExamPeekableQueue<E> {
LinkedList<E> li = new LinkedList<E>();
public ExamPeekableQueueImpl(){
}
public void enqueue(E e){
if(li.isEmpty()){
li.add(0, e);
}
else
li.add(e);
}
public E dequeue(){
li.pollFirst();
return null;
}
public void printlist(){
System.out.println(li.toString());
}
public E peekMedian(){
int var = (((li.size())/2)+1);
Collections.sort(li);
//Integer var2 = li.get(var);
System.out.println("the median is:" + li.get(var-1));
return null;
}
public E peekMaximum(){
Collections.sort(li);
System.out.println("the maximum is:" + li.getLast());
return null;
}
public E peekMinimum(){
Collections.sort(li);
System.out.println("the minimum is:" + li.getFirst());
return null;
}
public int size(){
li.size();
return 0;
}
}
Also I wanted to know is whether for implementing queues, LinkedList is faster or ArrayList or any other data structure.
Currently you have O(1) for insertion and O(nlogn) for
getMin/getMax/getMedian. You can move the logn from the getters to the insertion part by using a sorted data structure. Or you can leave the insertion as it is and optimizegetMin/getMaxby doing a linear search through the list and just storing the minimal value. ForgetMedianthere is nothing to do as you need a sorted set for that.A further optimization would be to store the min/max and update the two values during each insertion step. This will not have any (non-constant) change on insertion and will reduce your
getMin/getMaxto O(1). (thanks to Tedil)The same applies for
getMedian, where you would keep a sorted list in parallel to your linked list. You can then simply pick the median out of the middle of that list. Of course this will change insertion time to O(logn) or worse (depending on the list you use) and will also double the amount of storage space. So it is a more expensive optimization than the one forgetMin/getMax.