Question
Given the following incomplete implementation of a doubly linked list, fill in the implementation for the add(), remove(), and clear() methods import java.lang.IndexOutOfBoundsException; public class
Given the following incomplete implementation of a doubly linked list, fill in the implementation for the add(), remove(), and clear() methods
import java.lang.IndexOutOfBoundsException;
public class LinkedList
private Node head;
private Node tail;
private int size;
public LinkedList(){
// NOTE: head and tail are dummy nodes that simplify the code, but do not
// actually contain elements.
tail = new Node(null, null, null);
head = new Node(null, null, tail);
tail.setPrev(head);
size = 0;
}
// add the element to the end of the list
public void add(Anytype element){
}
//remove the node of the given index from the list
public void remove(int index) {
}
// clear the list
public void clear() {
}
public AnyType getElement(int index) {
Node current;
If ( index >= size ) {
throw new IndexOutOfBoundsException();
}
If ( index < size / 2 ) {
Current = head.next;
For ( int I = 0; I < index, i++) {
Current = current.next;
}
}
else { // the element is in the second half of the list
current = tail.prev;
for( int I = size 1; I > index; i++) {
current = current.prev;
}
}
return current.element;
private class Node{ //nexted class within our LinkedList implementation
private AnyType element;
private Node prev;
private Node next;
public Node(Anytype e, Node previousNode, Node nextNode) {
element = e;
prev = previousNode;
next = nextNode;
}
public void setPrev(Node previousNode) {
prev = previousNode;
}
public void setNext(Node nextNode) {
next = nextNode; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started