w3resource

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>

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

// Function to push a new node
void push_node(struct Node** head_ref, int new_data) {
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

// Function to merge alternate nodes of two linked lists
void merge_alternate_Nodes(struct Node** head1_ref, struct Node** head2_ref) {
    struct Node* p1 = *head1_ref;
    struct Node* p2 = *head2_ref;

    while (p1 != NULL && p2 != NULL) {
        struct Node* temp = p1->next;
        p1->next = p2;
        p2 = p2->next;
        p1->next->next = temp;
        p1 = temp;
    }

    *head2_ref = p2;
}

// Function to print a linked list
void displayList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    struct Node* head1 = NULL;
    struct Node* head2 = NULL;

    push_node(&head1, 1);
    push_node(&head1, 3);
    push_node(&head1, 5);
    push_node(&head1, 7);
    push_node(&head1, 9);

    push_node(&head2, 2);
    push_node(&head2, 4);
    push_node(&head2, 6);
    push_node(&head2, 8);
    push_node(&head2, 10);

    printf("First linked list: ");
    displayList(head1);

    printf("Second linked list: ");
    displayList(head2);

    merge_alternate_Nodes(&head1, &head2);

    printf("Merged linked list: ");
    displayList(head1);
}

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 :

Flowchart: Merge alternate nodes of two linked lists.
Flowchart: Merge alternate nodes of two linked lists.

C Programming Code Editor:

Previous: Delete alternate nodes of a singly linked list.
Next: Remove duplicates from a sorted singly linked list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.