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

Hi, I am trying to create a method that will take two Linked list and add the se

ID: 3539102 • Letter: H

Question

Hi, I am trying to create a method that will take two Linked list and add the second list to the first list


// assignment: Add this method

// This method should add all of the nodes in ll into
// the current list

public void addAll(LinkedList ll)
{
    //hint
    // go though all of the elements in ll adding
    // each to the current list
    // Throw exception when neccessary
   
    Node currentSecondList ==ll.first
      While(currentSecondList!-null)
    {
      current.SecondList = currentSecondList.next;
    }
}

// Thanks for the help

Explanation / Answer

This is another version of the same function, but in this version you don't need to add all nodes one by one, adding just the first node of second list to the last of the first list will do the job. The rest is explained in the comments.



// assignment: Add this method

// This mehtod should add all of the nodes in ll into

// the current list

/************************Updated by UDCSEIITB2014****************/

public void addAll(LinkedList ll) throws Exception

{

//hint

// go though all of the elements in ll adding

// each to the current list

// Throw exception when neccessary

Node current = this.first;//Node object for traversing the original first linked list

if(current == null)

throw new Exception("Empty Linked List");

//Traverse through the first list to find the last node

while(current.next != null){

current = current.next;

}

//current points to the last node after the for loop

current.next = ll.first;

/** Attach the last node of the first list with the first node of the second list

* You don't need to add all items one by one from second list to first list

* because all nodes of the second list are already connected and when you add the first node of second list

* to the first list, the whole list automatically gets added to the first list. This can be verified by

* the fact that last node is determined by the node whose next node is null.

* When you add the first node of second list to the first list, its next pointer still points to the second

* node of the second list. So, no need to add all nodes.

**/

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote