Answer to Question #270183 in C for Amit

Question #270183

Given two single linked lists, write a C code to merge their nodes together to make one list, taking nodes alternately between the two lists. So the output with {1, 2, 3} and {7, 13, 1} should yield {1, 7, 2, 13, 3, 1}. If either list runs out, all the nodes should be taken from the other list.

1
Expert's answer
2021-11-23T05:18:47-0500
#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int info;
    struct Node *next;
};
void add(struct Node ** head_ref, int new_data)
{
    struct Node* new_node =
           (struct Node*) malloc(sizeof(struct Node));
    new_node->info  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)  = new_node;
}
void display(struct Node *head)
{
    struct Node *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->info);
        temp = temp->next;
    }
    printf("\n");
}
void merge(struct Node *first, struct Node **sec)
{
     struct Node *first_curr = first, *sec_curr = *sec;
     struct Node *first_next, *sec_next;
     while (first_curr != NULL && sec_curr != NULL)
     {
         first_next = first_curr->next;
         sec_next = sec_curr->next;
 
         sec_curr->next = first_next;  
         first_curr->next = sec_curr; 
         first_curr = first_next;
         sec_curr = sec_next;
    }
 
    *sec = sec_curr; 
}
 
int main()
{
     struct Node *first = NULL, *sec = NULL;
     add(&first, 3);
     add(&first, 2);
     add(&first, 1);
     printf("First Linked List:\n");
     display(first);
 
     add(&sec, 1);
     add(&sec, 13);
     add(&sec, 7);
     printf("Second Linked List:\n");
     display(sec);
 
     merge(first, &sec);
 
     printf("Modified First Linked List:\n");
     display(first);
 
     printf("Modified Second Linked List:\n");
     display(sec);
 
     getchar();
     return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS