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 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.
Solution
first let me explain you the following part of the code :
Node newNode = new Node(pData, getTail(), null); //1
if (isEmpty()) setHead(newNode); //2
else getTail().setNext(newNode); //3
setTail(newNode); //4
-> In line 1, a new node is created with the value of pData.
-> now since the new node is created, we will have to add this new node called newNode, to the list.
-> now we have two scenarios :
scenario 1 : the list is empty : In this scenario, we need to simply set this newNode as our Head node.
the line 2 is doing the same thing. first it is checking whether the list is empty or not. if it is empty, then call setHead() method & pass newNode as a parameter to set the newNode as the Head node.
scenario 2 : the list is not empty, that is, the list already contains some nodes.
In this scenario, we need to add the newNode to the end of the list.
the line 3 is doing the same thing. it is calling the getTail() to get the tail of the list which is the last node of the list. and then setting the next pointer of the this node to point to the newNode.
In line 4, the last node which is now the newNode is set as a tail of the list.
Now, if change the logic by swapping LINE1 and LIINE2, it change the behavior of how the elements are adding. Now the code will not check first, if the list is empty or not, it will directly try to get the tail of the list. so the code will fail in the case where the list is empty. There is no node in the list & if you try to set the next pointer of the tail node to point to newNode, it will cause the program to fail.
feel free to ask if you have any doubt. :)
