In: Computer Science
//C++
a. 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 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.
b. Write the definition of the function template mergeLists to implement the operation mergeLists.
//C++ program
#include<iostream>
using namespace std;
template <typename T>
class orderedLinkedList{
private:
struct node{
T data;
struct
node*next;
};
struct node* head;
public:
orderedLinkedList(){
head =
NULL;
}
void add(T data){
struct node*
newNode = new node;
newNode->data
= data;
newNode->next
= NULL;
if(head ==
NULL){
head = newNode;
return;
}
struct node*
current = head;
while(current->next)current = current->next;
current->next
= newNode;
}
void print(){
struct node*
current = head;
while(current){
cout<<current->data << " ";
current = current->next;
}
}
void
mergeLists(orderedLinkedList<T>
&list1,orderedLinkedList<T> &list2){
struct node*
left = list1.head;
struct node*
right= list2.head;
struct node*
newNode,*tail = head;
int data;
while(left !=
NULL && right != NULL){
if(left->data < right->data){
data = left->data;
left = left->next;
}
else{
data = right->data;
right = right->next;
}
newNode = new node;
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}
else{
tail->next =
newNode;
}
tail = newNode;
}
while(left !=
NULL){
newNode = new node;
newNode->data = left->data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}
else{
tail->next =
newNode;
}
tail = newNode;
left = left->next;
}
while(right !=
NULL){
newNode = new node;
newNode->data = right->data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}
else{
tail->next =
newNode;
}
tail = newNode;
right = right->next;
}
}
};
int main(){
orderedLinkedList<int> newList;
orderedLinkedList<int> list1;
orderedLinkedList<int> list2;
list1.add(2);
list1.add(6);
list1.add(7);
list2.add(3);
list2.add(5);
list2.add(8);
newList.mergeLists(list1, list2);
cout<<"Merged list\n";
newList.print();
return 0;
}