I am currently preparing for my upcoming exam and there was one tast from an older exam, where we have been given an ADTQueue
public interface ADTQueue<T> { public void enq(T element);
public void deq();
public T front();
public boolean empty(); }
we now have to implement the class Queue as well as an inner class with the constructor ListElement(T element) and some methods in it...
I have made an implementation, this is my following code:
public class Queue<T> implements ADTQueue<T> {
private ListElement<T> head;
private ListElement<T> tail;
public Queue(){
head=null;
tail=null;
}
public void enq (T element){
if (empty()){
head= new ListElement(element);
tail= new ListElement(element);
}
tail.nextElement=new ListElement(element);
tail=tail.nextElement;
}
public void deq(){
if (empty()){
throw new Exception();
}
T firstElement=front();
head=head.nextElement;
if (head==null){
tail = null;
}
}
public T front(){
if(empty()){
return null;
}
return head.element;
}
public boolean empty(){
return (head==null);
}
public class ListElement<T>{
private T element = null;
private ListElement<T> nextElement = null;
public ListElement(T element) {
this.element = element;
}
public T getElement() {
return element;
}
public ListElement<T> getNextElement() {
return nextElement;
}
public void setNextElement(ListElement<T> nextElement) {
this.nextElement = nextElement;
}
}
I would like to know, if it is correct what I did and if I could have done it better. Also, how would it look like, if I wanted to do the same but with double linked list? I know, I need also a get- and setPreviousElement, but I am not sure, what is going to change in the enqueue and dequeue methods... I would be really happy, if you guys could give some advice thx in advance
1) Suggestion for better Return Types:
public boolean enqueue(T element)
should be boolean, instead of Void.
public T dequeue();
should be T, instead of Void.
2) Link - a single Object in a linked list.
Lines 3+4:
Upon an arrival of a new element, you create 2 Different Links with the same Data (T), instead of 1 Link (that also the head & tail points to this Link).
Lines 5+6:
I think you forgot the wrap the rest of the code with else{...}
.
Before changes:
1 public void enq (T element){
2 if (empty()){
3 head= new ListElement(element);
4 tail= new ListElement(element);
}
5 tail.nextElement=new ListElement(element);
6 tail=tail.nextElement;
}
After suggested changes:
1 public void enq (T element){
2 if (empty()){
3 head= new ListElement(element);
4 tail= head;
5 }else{
6 tail.nextElement=new ListElement(element);
7 tail=tail.nextElement;
}
}