﻿ C Program: Merge alternate nodes of two linked lists

# C Exercises: Merge alternate nodes of two linked lists

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

Write a C program to to merge alternate nodes of two singly linked lists.

Sample Solution:

C Code:

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

// Structure defining a node in a singly linked list
struct Node {
int data;           // Data stored in the node
struct Node* next;  // Pointer to the next node
};

// Function to push a new node to the front of the linked list
void push_node(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));  // Allocate memory for a new node
new_node->data = new_data;  // Assign data to the new node
new_node->next = (*head_ref);  // Make the new node point to the current head
(*head_ref) = new_node;  // Update the head to point to the new node
}

// Function to merge alternate nodes of two linked lists
struct Node* p1 = *head1_ref;  // Pointer for the first list
struct Node* p2 = *head2_ref;  // Pointer for the second list

while (p1 != NULL && p2 != NULL) {
struct Node* temp = p1->next;  // Store the next node of the first list
p1->next = p2;  // Make the current node of the first list point to the current node of the second list
p2 = p2->next;  // Move to the next node in the second list
p1->next->next = temp;  // Make the node from the second list point to the next node of the first list
p1 = temp;  // Move to the next node in the first list
}

*head2_ref = p2;  // Update the second list's head to the remaining nodes
}

// Function to print a linked list
printf("%d ", head->data);  // Print the data of the current node
}
printf("\n");
}

// Main function to demonstrate merging alternate nodes of two linked lists
int main() {
struct Node* head1 = NULL;  // Initialize the first linked list as empty
struct Node* head2 = NULL;  // Initialize the second linked list as empty

// Push elements to the first linked list

// Push elements to the second linked list

return 0;
}
```
```

Sample Output:

```First linked list: 9 7 5 3 1
Second linked list: 10 8 6 4 2
Merged linked list: 9 10 7 8 5 6 3 4 1 2
```

Flowchart :

C Programming Code Editor:

What is the difficulty level of this exercise?

﻿