# Merge two sorted linked lists using C++.

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## Problem statement

Given 2 sorted singly linked list. Write a function to merge given two sorted linked lists

List1: 10->15->17->20
List2: 5->9->13->19
Result: 5->9->10->13->15->17->19->20

## Algorithm

1. Traverse both lists
1.1. If list1->data < list2->data
1.1.1 Add list1->data to new list and increment list1 pointer
1.2 If list2->data < list1->data
1.2.1 Add list2->data to new list and increment list2 pointer
2. Repeat procedure until both lists are exhausted
3. Return resultant list

## Example

#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr))
using namespace std;
struct node {
int data;
struct node *next;
};
node *createList(int *arr, int n){
p = head = new node;
for (int i = 1; i < n; ++i) {
p->next = new node;
p = p->next;
p->data = arr[i];
p->next = NULL;
}
}
while (head != NULL) {
cout << head->data << " ";
}
cout << endl;
}
node *result = NULL;
if (head1 == NULL) {
}
if (head2 == NULL) {
}
} else {
}
return result;
}
int main(){
int arr1[] = {10, 15, 17, 20};
int arr2[] = {5, 9, 13, 19};
head1 = createList(arr1, SIZE(arr1));
head2 = createList(arr2, SIZE(arr1));
cout << "First sorted list: " << endl;
cout << "Second sorted list: " << endl;
cout << "Final sorted list: " << endl;
displayList(result);
return 0;
}

## Output

When you compile and execute the above program. It generates the following output −

First sorted list:
10 15 17 20
Second sorted list:
5 9 13 19
Final sorted list:
5 9 10 13 15 17 19 20