Hary
Hary

Reputation: 21

merging two linked list

i have problem in merging 2 list, so what i (think) am doing is. assign list A to current, go to last node of current, add list B to current, assign current to head2 and finally print. but when i run it nothing comes out, the head2 list still null

#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;

void print_list(node_t * head);
node_t* merge(node_t *head,node_t *head1);

int main(){
int number;
node_t * head = NULL;
node_t * head1 = NULL;

//inputA
//inputB

printf("merged list is : \n");
print_list(merge(head,head1));
printf("\n");   
return 0;
}

node_t *merge(node_t *head,node_t *head1){
     node_t * current = head;
     while(current->next != NULL){
     current = current->next;
     }
     current->next = head1;
     return current;    
}
void print_list(node_t * head) {
node_t * current = head;

while (current != NULL) {
    printf("%d ", current->val);
    current = current->next;
    }
}

EDIT : the head is list A and head1 is list B, already have some data. it will only keep the last node of A ex. A = 1 2 3 ,B = 4 5 6 return 3 4 5 6

Upvotes: 0

Views: 112

Answers (2)

Stian Skjelstad
Stian Skjelstad

Reputation: 2335

I saw to problems with merge:
* It would segfault if the left head was NULL.
* It returned the merge-point, and not the real new common head.

node_t *merge(node_t *head,node_t *head1){
     if (head == NULL)
         return head1;
     node_t * current = head;
     while(current->next != NULL){
     current = current->next;
     }
     current->next = head1;
     return head;
}

Upvotes: 0

Pemdas
Pemdas

Reputation: 543

Two issues:

merge is passing a copy of head2, so the head2 in main will not change. You need to pass a pointer to head2.

void merge(struct node *head,struct node *head1,struct node **head2)
{ 
    //the merge is ok, but the beginning of the list
    //is head not head1

    // dereference the pointer to head2 to change
    // the value of head2 in main.
    *head2 = head;
}

Also, this is really an append operation not a merge.

Upvotes: 0

Related Questions