Please help with Merging a linked list Add the following operation to the class
ID: 674439 • Letter: P
Question
Please help with Merging a linked list
Add the following operation to the class orderedLinkedList:
void mergeLists (orderedLinkedList &list1, orderedLinkedList &list2); // This function creates a new list by merging the
// elements of list1 and list2.
// Postcondition: first points to the merged list; list1 and list2 are empty
Example: Consider the following statements:
orderedLinkedList newList; orderedLinkedList list1;
orderedLinkedList list2;
Suppose list1 points to the list with the elements 2 6 7 and list2 points to the list with the elements 3 5 8. The statement: newList.mergeLists(list1, list2); Creates a new linked list with the elements in the order 2 3 5 6 7 8 and the object newList points to this list. Also, after the preceding statement executes, list1 and list2 are empty. Write the definition of the function template mergeLists to implement the operation mergeLists
Thank you,
Explanation / Answer
void mergeLists(orderedLinkedList &list1, orderedLinkedList &list2){
orderedLinkedList newList;
//if liat empty returning another list without merging
if(list1 == null) return list2;
if(list2 == null) return list1;
newList = list1; //firstly concatenating list1 to new list...
//next we will concat new list
while(list2.next != null){
newList.next = list2.next; //concatenating
list2 = list2.next;
}
return newList;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.