Consider the following code which implements the add method
Solution
Here is the code to add the node only at the end of the list, and not anywhere else.
public void add(int pIndex, Integer pData) throws IndexOutofBoundsException
{
/*if(pIndex < 0 || pIndex > getSize()) //If the index is out of the size of list.
throw new IndexOutofBoundsException();*/
//if(pIndex == getSize()) //adding a node to the end of the list.
{
//This module adds element to the end of the list. So, removing all the remaining blocks will do the needful.
//Instead of removing, I just commented out the code, so that only this part will be compiled/executed.
Node newNode = new Node(pData, getTail(), null);
if(isEmpty())
setHead(newNode);
else
getTail().setNext(newNode);
}
/* else
{
Node node = getNodeAt(pIndex);
Node newNode = new Node(pData, node.getPrev(), node);
if(pIndex != 0)
node.getPrev().setNext(newNode);
node.setPrev(newNode);
if(pIndex == 0)
setHead(newNode);
}*/
setSize(getSize() + 1);
}
