Consider the following code which implements the add method

Consider the following code which implements the add method in the DList class from the course videos: public void add (int pindex, integer pData) throws IndexOutof BoundsException {if (pIndex getSize()) throw new IndexOutOfBoundsException (); if (pIndex == getSize ()) {//adding node to the end of the list Node newNode = new Node(pData, getTail (), null); if (is Empty ()) setHead (newNode);//////////LINE 1 else getTail (). setNext (newNode);//////////LINE 2 setTail (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) setHeasd (newNode);} setSize (getSize () + 1);} Modify the method so that it adds nodes to the end of the linked list.

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);
}

 Consider the following code which implements the add method in the DList class from the course videos: public void add (int pindex, integer pData) throws Index

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site