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.
#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;
}
Comments
Leave a comment