题目二(链表合并)

#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode* next;
}LNode, * LinkList;//LinkList为指向结构体LNode的指针类型
LinkList read()
{
    int len = 0;
    int num = 0;
    LinkList h = NULL;
    LinkList Last = NULL;
    scanf_s(" %d", &len);
    if (len == 0)
        return NULL;
    h = (LinkList)malloc(sizeof(LNode));
    h->next = NULL;
    Last = h;
    while (len)
    {
        scanf_s("%d", &num);
        LinkList node = (LinkList)malloc(sizeof(LNode));
        node->data=num;
        node->next = NULL;
        Last->next = node;
        Last = node;
        len--;
    }
    return h;
}
void Print(LinkList L)
{
    if (L->next == NULL)
    {
        printf("NULL\n");
        return;
    }
    L = L->next;
    while (L != NULL)
    {
        printf("%d--", L->data);
        L = L->next;
    }
}
LinkList Merge(LinkList L1, LinkList L2)
{
    if (!L1 && !L2)
        return NULL;
    LinkList P1 = L1->next;
    LinkList P2 = L2->next;
    LinkList L3 = (LinkList)malloc(sizeof(LNode));
    //LinkList p3 = new LNode;
    L3->next = NULL;
    LinkList P3 = L3;
    while (P1 && P2)
    {
        if (P1->data < P2->data)
        {
            P3->next=P1;
            P1 = P1->next;
        }
        else
        {
            P3->next = P2;
            P2 = P2->next;
        }
        P3 = P3->next;
    }
    if (P1)
    {
        P3->next = P1;
    }
    if (P2)
    {
        P3->next = P2;
    }
    L1->next = NULL;
    L2->next = NULL;
    return L3;
}
void MergeList_L(LinkList& La, LinkList& Lb, LinkList& Lc)
{
    LinkList pa = La->next;
    LinkList pb = Lb->next,pc;
    pc = Lc = La;
    while (pa && pb)
    {
        if (pa->data <= pb->data)
        {
            pc->next = pa;
            pc = pa;
            pa = pa->next;
        }
        else
        {
            pc->next = pb;
            pc = pa;
            pa = pa->next;
        }
        pc->next = pa ? pa : pb;
    }
    
}
int main()
{
    LinkList L1, L2,L;
    L1 = read();
    L2 = read(); 
    //L = Merge(L1, L2);
    MergeList_L(L1, L2, L);
    Print(L1);
    printf("\n");
    Print(L2);
    printf("\n");
    Print(L);
    printf("\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值