Answer:
DoubleList()
{
numElements=0;
front=rear=null;
}
public void addData(int index,T newData) throws InvalidPositionException
{
if(index<0||index>numElements)
throw new InvalidPositionException();
DoubleNode newNode=new DoubleNode(newData);
numElements++;
// if there is no node initially
if(front==null)
{
front=rear=newNode;
return;
}
// get the node after which we have to add the new node
DoubleNode pre=null,temp=front;
while(temp!=null&&index>0)
{
pre=temp;
temp=temp.next;
index--;
}
if(pre==null)
{
newNode.next=front;
front.previous=newNode;
front=newNode;
}
else
{
newNode.next=temp;
newNode.previous=pre;
pre.next=newNode;
}
}
public DoubleNode<T> getNode(int index)
{
if(index<0||index>=numElements)
try {
throw new InvalidPositionException();
} catch (InvalidPositionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DoubleNode temp=front;
// traverse the list till we reach at the given index and return the address of that node
while(temp!=null&&index>0)
{
temp=temp.next;
index--;
}
return temp;
}
public void removeData(int index) throws InvalidPositionException
{
DoubleNode temp;
temp = getNode(index); // get the reference to the node at the given index
numElements--;
// if there is only one node in the linkedlist then after removing there is no node
if(numElements==0)
{
front=rear=null;
}
else
{
temp.previous.next=temp.next;
if(temp.next!=null)
temp.next.previous=temp.previous;
}
}
public T getData(int index) throws InvalidPositionException
{
DoubleNode temp=null;
temp = getNode(index); // get the Node from where we have to get the data
return (T) temp.data;
}
public void setData(int index ,T newData) throws InvalidPositionException
{
DoubleNode temp;
temp = getNode(index); // get the node where we have to set the newData
temp.data=newData;
}
Step-by-step explanation:
See the complete code in answer section.