﻿ C Program: Combine two sorted singly linked lists

# C Exercises: Combine two sorted singly linked lists

## C Singly Linked List : Exercise-13 with Solution

Write a C program to merge two sorted singly linked lists into a single sorted linked list.

Sample Solution:

C Code:

``````#include<stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

// Function to create a new node
struct Node* new_Node(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}

// Function to merge two sorted linked lists into a single sorted linked list
// If either of the linked lists is empty, return the other list

// Create a dummy node to store the result
struct Node dummy;
struct Node* tail = &dummy;

// Traverse both linked lists, adding smaller elements to the result list
} else {
}
tail = tail->next;
}

// If either of the linked lists is not fully processed, append the rest of the elements

// Return the result
return dummy.next;
}

// Function to display a linked list
}
printf("\n");
}

int main() {
struct Node* list1 = new_Node(1);
list1->next = new_Node(3);
list1->next->next = new_Node(5);
list1->next->next->next = new_Node(7);
struct Node* list2 = new_Node(2);
list2->next = new_Node(4);
list2->next->next = new_Node(6);
displayList(list1);
displayList(list2);
struct Node* result = mergeTwoLists(list1, list2);
printf("\nAfter merging the said two sorted lists:\n");
displayList(result);
return 0;
}
```
```

Sample Output:

```Two sorted singly linked lists:
1 3 5 7
2 4 6

After merging the said two sorted lists:
1 2 3 4 5 6 7
```

Flowchart :

C Programming Code Editor:

What is the difficulty level of this exercise?

﻿