简体   繁体   English

如何合并 C 中的两个链表?

[英]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?你能详细解释一下吗,我怎样才能正确合并两个链表?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM