(Data Structures Using C++ Book, Author:Liang) Merge Linked Lists Add the follow
ID: 3529131 • Letter: #
Question
(Data Structures Using C++ Book, Author:Liang) Merge Linked Lists 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. Also write a program to test your function.
Explanation / Answer
Merge linked list...!!! node* MergeSort(node *my_node) { node *secondNode; if (my_node == NULL) return NULL; else if (my_node->next == NULL) return my_node; else { secondNode = Split(my_node); return Merge(MergeSort(my_node),MergeSort(secondNode)); } } node* Merge(node* firstNode, node* secondNode) { if (firstNode == NULL) return secondNode; else if (secondNode == NULL) return firstNode; else if (firstNode->number number) //if I reverse the sign to >=, the behavior reverses { firstNode->next = Merge(firstNode->next, secondNode); return firstNode; } else { secondNode->next = Merge(firstNode, secondNode->next); return secondNode; } } node* Split(node* my_node) { node* secondNode; if (my_node == NULL) return NULL; else if (my_node->next == NULL) return NULL; else { secondNode = my_node->next; my_node->next = secondNode->next; secondNode->next = Split(secondNode->next); return secondNode; } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.