Consider the following code which implements the add method in the DList class f
ID: 3826437 • 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 IndexOutOfBoundsException {
if (pIndex < 0 || pIndex > getSize())
throw new IndexOutOfBoundsException();
if (pIndex == getSize()) { //adding node to the end of the list
Node newNode = new Node(pData, getTail(), null);
if (isEmpty())
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)
setHead(newNode);
}
setSize(getSize() + 1);
}
Explain what will happen if the lines indicated are swapped.
Explanation / Answer
Hi,
As per normal flow of your code the "Line 1" is inserting a node at the beginning of the linked list if the list is empty. And Line 2 will get executed if the list is non empty. Line 2 will make the last node of the linked list to point to the newly inserted node.
Now, if we swap the Line 1 with Line 2, then as the list is empty,the new node is inserted as the first node. If line 2 is swapped by line 1 then everytime a new node is inserted in a non-empty list, the new node is inserted at the beginning of the list.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.