Consider the following code which implements the add method in the DList class f
ID: 3795126 • Letter: C
Question
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.Explanation / Answer
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);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.