两升序/降序链表的合并

两升序链表l1 l2合并为一个链表存放在l1

这是当时初学链表时写的一个简单的有序链表合并
大致的思路是这样

代码

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

测试结果

猜你喜欢

转载自blog.csdn.net/codefarmer__/article/details/80215847