Part A: Coding
2. Implement Doubly Linked List add method which add an element to a specific position. - It’s an instance method that takes a position and an element, then adds the element to this specific position and shifts the element currently at this position and any subsequent elements to the right. It throws an exception if the position is out of bound. It traverses the list from header if the position is closer to the header and traverses the list from trailer otherwise.
Given Codes:
/**
* * Student:
* */
public class A1LinkedList{
public static void main(String argc[]){
DLinkedList<String> dl = new DLinkedList<>();
dl.add("Three",0);
dl.add("Five",1);
dl.add("One",0);
dl.add("Two",1);
dl.add("Four",3);
dl.print();
class DLinkedList<E>{
private static class DNode<E>{
private E element;
private DNode<E> prev;
private DNode<E> next;
public DNode(E e){
this(e, null, null);
}
public DNode(E e, DNode<E> p, DNode<E> n){
element = e;
prev = p;
next = n;
}
public E getE(){
return element;
}
public DNode<E> getPrev(){
return prev;
}
public DNode<E> getNext(){
return next;
}
public void setE(E e){
element = e;
}
public void setPrev(DNode<E> p){
prev = p;
}
public void setNext(DNode<E> n){
next = n;
}
}
private DNode<E> header;
private DNode<E> trailer;
private int size;
public DLinkedList(){
header = new DNode<E>(null);
trailer = new DNode<E>(null, header, null);
header.setNext(trailer);
size = 0;
}
public void print(){
DNode<E> temp = header.getNext();
while (temp != trailer){
System.out.print(temp.getE().toString() + ", ");
temp = temp.getNext();
}
System.out.println();
}
}
class Node<E>
{
E data;
Node next;
Node prev;
public Node(E data, Node next, Node prev)
{
this.data = data;
this.next = next;
this.prev = prev;
}
}
class DoublyLinkedList<E>
{
private Node first;
private int size;
public void add(int index, E value)
{
if(index > size || index < 0)
{
throw new IndexOutOfBoundsException();
}
if (first == null)
{
Node n = new Node(value, null, null);
n.next = n;
n.prev = n;
first = n;
}
else
{
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
Node n2 = new Node(value, current, current.prev);
current.prev.next = n2;
current.prev = n2;
if(index == 0)
{
first = n2;
}
}
size++;
}
public void print(){
Node current = first;
for (int i = 0; i < size; i++)
{
System.out.println(current.data);
current = current.next;
}
}
}
class A{
public static void main(String[] args)throws Exception
{
DoublyLinkedList dl = new
DoublyLinkedList();
dl.add(0,20);
dl.add(1,10);
dl.add(2,5);
dl.add(1,25);
dl.print();
}
}



Part A: Coding 2. Implement Doubly Linked List add method which add an element to a...