如何在 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;
}

我知道这是完全错误的。但不知何故,这对我来说是有道理的。可能,我误解了链接列表概念。您能否详细向我解释一下,如何正确合并两个链接列表?

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;
}
}

相关内容

  • 没有找到相关文章

最新更新