In this assignment, you will implement a referenced based Deque. To accomplish t
ID: 3911571 • Letter: I
Question
In this assignment, you will implement a referenced based Deque. To accomplish this, you will create first create an inner (i.e. inside the Deque class) class Node. The Node class will have the attributes: o T item o Node next You will also create a class Dequethat has the following attributes: » Node head o Node tail int nrltems Also, it will have the following methods » A constructor that creates an empty deque. e void addFirst(T item) - adds at the head e T removeFirst) - removes from the head T getFirst() head e void addLast(T item) returns the element at the - adds at the tail T removeLast() -removes from the tail T getLast() tail int size() in the deque e boolean isEmpty()true if empty false otherwise » String toString()- returns a String representation of the elements in the deque e void clear() returns the element at the returns the number of items empties the deque.Explanation / Answer
public class Deque<T> {
private Node head;
private Node tail;
private int nrItems;
private int size;
public Deque() {
head = null;
tail = null;
size= 0;
}
public void addFirst(T item, int index) {
if (index > size) {
throw Exception("The index is greater than the currentent size [" + size + "].");
} else {
Node temp = new Node(items);
Node current = getNode(index);
if (index == 0) {
temp.setNext(head);
head = temp;
tail = head;
} else {
temp.setNext(current.getNext());
current.setNext(temp);
}
if ( index == size- 1 ) {
tail.setNext(temp);
tail = temp;
}
}
size++;
}
public T replaceFirst(T data, int index) {
getNode(index).setItems(items);
}
public T removeFirst(int index) {
if (index == 0) {
head = head.getNext();
} else {
getNode(index).setNext(getNode(index).getNext().getNext());
}
this.size--;
}
private Node getNode(int index) {
if ( index > size) {
throw Exception("The index is greater than the currentent size [" + size + "].");
Node current = head;
for (int i = 1; i < index; i++) {
current = current.getNext();
}
return current;
}
public T getLast(int index) {
return getNode(index).getItems();
}
public int nrItems() {
return this.nrItems;
}
public boolean isEmpty(){
return this.isEmpty;
}
public int size() {
return this.size;
}
public String toString() {
StringBuilder b = new StringBuilder();//b=builder
Node current = head;
while( current != null ) {
b.append("[" + current.getItems() + "]");
current = current.getNext();
}
return b.toString();
}
public void clear(){
return this.clear;
}
public class Node {
Node next;
T item;
public Node(T item) {
this(item, null);
}
public Node(T item, Node next) {
this.next = next;
this.item = item
}
public Object getItem() {
return this.item;
}
public void setItem(T item) {
this.item = item;
}
public Node getNext() {
return this.next;
}
public void setNext(Node nextNode) {
this.next = nextNode;
}
}