Question: Write an add method for the following DLL, it would add the element to a specific position . Use the following code to test your
Write an add method for the following DLL, it would add the element to a specific position.
Use the following code to test your answer:
// Should give you the result from zero to five in Test#1
// throw an exception if the position is out of bound in Test#2
Test#1 DLLd = new DLL<>(); d.add("TWO",0); d.add("FOUR",1); d.add("ZERO",0); d.add("ONE",1); d.add("THREE",3); d.print();
Test#2:
d.add("TWO",0); d.add("FOUR",1); d.add("ZERO",0); d.add("ONE",1); d.add("THREE",6); d.print();
public class DLL < E > {
private static class Node < E > {
private E ele;
private Node < E > pre;
private Node < E > next;
public Node(E e) {
this(e, null, null);
}
public Node(E e, Node < E > p, Node < E > n) {
ele = e;
pre = p;
next = n;
}
public E getE() {
return ele;
}
public Node < E > getPre() {
return pre;
}
public Node < E > getNext() {
return next;
}
public void setE(E e) {
ele = e;
}
public void setPrev(Node < E > p) {
pre = p;
}
public void setNext(Node < E > n) {
next = n;
}
}
private Node < E > first;
private Node < E > last;
private int size;
public DLL() {
first = new Node < E > (null);
last = new Node < E > (null, first, null);
first.setNext(last);
size = 0;
}
public void print() {
Node < E > tempo = first.getNext();
while (tempo != last) {
System.out.print(tempo.getE().toString() + ", ");
tempo = tempo.getNext();
}
System.out.println();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
