Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the instance method swapFirst for the class LinkedList that has the fo

ID: 3891482 • Letter: I

Question

Implement the instance method swapFirst for the class LinkedList that has the following characteristics . An instance always starts off with a dummy node, which serves as a marker for the start of the list. The dummy node is never used to store data. The empty list consists of the dummy node only . In the implementation for this question, the nodes of the list are doubly linked; . In this implementation, the list is circular, i.e. the reference next of the last node of the list is pointing at the dummy node, the reference prev of the dummy node is pointing at the last element of the list. In the empty list, the dummy node is the first and last node of the list, its references prev and next are pointing at the node itself; * Since the last node is easily accessed, because it is always the previous node of the dummy node, the header of the list does not have (need) a tail pointer The method swapFirst exchanges the order of the first two nodes of the list. . This question assesses your understanding of linked structures. Because of that, you cannot simply exchange the values. You need to exchange the order of the two objects of type Node * Likewise, you cannot use the methods of the class LinkedList. In particular, you cannot use the methods add0 or remove0 . The method throws the exception IllegalStateException if the size of the list is less than two (2) Here is the memory diagram of the list before and after a call to the method swapFirst. We have used two different kinds of dotted lines to draw the first two nodes to identify the work to be done head head size size (before) (after)

Explanation / Answer

Here is the function:

You just have to change the previous and next links of nodes head and the first two nodes(A and B) after head.

Also, the previous link of the third node(C) is changed from second node(B) to first node(A). That has to be changed too.


       public void swapFirst() throws IllegalStateException{
          
           if(this.size<2){
               throw new IllegalStateException("List Size less than 2");
           }
           else{
               Node<T> first_node = this.head.next;
               Node<T> second_node = this.head.next.next;
               Node<T> third_node = this.head.next.next.next;
               this.head.next = second_node;
               first_node.next = third_node;
               second_node.next = first_node;
               first_node.prev = second_node;
               second_node.prev = this.head;
               third_node.prev = first_node;
           }
       }