'How can I merge two linked-list in C?
typedef struct Node{
int val;
struct Node *next;
}Node;
/* n1 and n2, head of two linked list */
void merge(Node *n1,Node *n2)
{
Node *tail=n1;
while(tail->next!=NULL)
tail=tail->next;
tail->next=n2;
}
I know this is completely wrong. But somehow, this makes sense to me. Probably, I misunderstood something with linked-list concepts. Can you please, explain to me in details, How can I properly merge two linked-list?
Solution 1:[1]
void merge(Node *first, Node *second){
Node *third = NULL, *last = NULL;
if(first->data>second->data){
third=last=second;
second=second->next;
last->next=NULL;
}
else{
third=last=first;
first=first->next;
last->next=NULL;
}
while(first && second){
if(first->data<second->data){
last->next=first;
last = first;
first = first->next;
last->next = NULL;
}
else{
last->next=second;
last = second;
second = second->next;
last->next = NULL;
}
}
if(first){
last->next = first;
}
else{
last->next = second;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
