Merge of two ascending/descending linked lists

Two ascending linked lists l1 and l2 are merged into one linked list and stored in l1

This is a simple ordered linked list merge written when I was a beginner at that time. The
general idea is this

code

#include <stdio.h>  
#include <stdlib.h>  
typedef struct NODE{  
    int num;  
    struct NODE *next;  
}node;  
node *get()//给链表赋值  
{  
    node *head=NULL,*p,*t=head;  
    while(1){  
        p=(node *)malloc(sizeof(node));  
        p->next=NULL;  
        scanf("%d",&p->num);  
        if(p->num==0){  
            free(p);  
            break;  
        }  
        if(head==NULL)  
            head=p;  
        else  
        {  
            t->next=p;  
        }  
        t=p;  
    }  
    return head;  
}  
void show(node*a)//打印链表内容  
{  
    while(a){  
        printf("%d ",a->num);  
        a=a->next;  
    }  
    printf("\n");  
}  
node *ad(node* l1,node *l2)//合并两链表  
{  
    node *head;  
    node *p;  
    if(l1->num<=l2->num){  
        head=l1;  
        p=l1;  
        l1=l1->next;  
    }  
    else{  
        head=l2;  
        p=l2;  
        l2=l2->next;  
    }  
    while(l1 && l2){  
        if(l1->num<=l2->num){  
            p->next=l1;  
            p=l1;  
            l1=l1->next;  
        }  
        else{  
            p->next=l2;  
            p=l2;  
            l2=l2->next;  
        }  
    }  
    if(l1==NULL)  
        p->next=l2;  
    else  
        p->next=l1;  
    return head;  
}  
int main(void){  
    printf("输入第一个链表(0表示结束)\n");  
    node *l1=get();  
    printf("输入第二个链表(0表示结束)\n");  
    node *l2=get();  
    printf("原链表为\n");  
    show(l1);  
    show(l2);  
    l1=ad(l1,l2);//合并后的链表赋给l1  
    printf("合并链表后为\n");  
    show(l1);  
    return 0;  
}  

Test Results

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325720952&siteId=291194637