单链表升序合并

#include<stdio.h>
#include<stdlib.h>
#define NULL 0

typedef struct LNode
{
    struct LNode *next;
    int data;
}LNode,*list;

void createList(list &l,int n)
{
    list p,q;
    l=(list)malloc(sizeof(LNode));
    p=l;
    for(int i=0;i<n;i++)
    {
        q=(list)malloc(sizeof(LNode));
        scanf("%d",&q->data);
        p->next=q;
        p=q;
    }
    p->next=NULL;
}

void merge(list &A,list &B,list &C)
{
    list p,q,r;
    p=A->next;
    q=B->next;
    C=A;
    C->next=NULL;
    free(B);
    r=C;
    while(p&&q)
    {
        if(p->data<=q->data)
        {
            r->next=p;
            p=p->next;
            r=r->next;
        }
        else
        {
            r->next=q;
            q=q->next;
            r=r->next;
        }
    }
    if(p)r->next=p;
    if(q)r->next=q;
}

void printList(list &l)
{
    list p;
    p=l;
    while(p->next!=NULL)
    {
        p=p->next;
        printf("%d ",p->data);
    }
    printf("\n");
}

void main()
{
    list A,B,C;
    int n,x;
    scanf("%d",&n);
    printf("input list A:\n");
    createList(A,n);
    printf("input list B:\n");
    createList(B,n);
    merge(A,B,C);
    printf("Merged:\n");
    printList(C);
}

你可能感兴趣的:(单链表)