递增有序单链表合并

1.实现将两个带头结点的链表L1和L2进行连接,连接后的链表仍然使用原来的存储空间;结果为链表L2连接到L1的末尾。

思路:找到链表L1的尾节点,使其指针域指向下一个链表的头结点(同时将链表L2所占用的内存空间进行回收)。

合并之前:
这里写图片描述

合并之后:
这里写图片描述

#include "stdafx.h"
#include <iostream>
using namespace std;

typedef int ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode;

//创建链表
LNode* Create(void)
{
    LNode *Head, *current;
    Head = current = (LNode *)malloc(sizeof(LNode));
    Head->next = NULL;

    ElemType d;
    LNode *temp;
    char s;
    while (1)
    {
        temp = (LNode *)malloc(sizeof(LNode)); //为新节点分配内存空间
        scanf("%d", &temp->data);
        current->next = temp;
        current = temp;
        s = getchar();           //s用来接收是否是回车  
        if (s == '\n') { break; }
    }
    current->next = NULL;  //最后尾指针为NULL
    return Head;
}

//输出链表
void List(LNode *L)
{
    LNode *p;
    p = L->next;  //
    while (p != NULL)
    {
        printf("%2d", p->data);
        p = p->next;
    }
}

void Merge(LNode *&A, LNode *&B, LNode *&C)
{
    LNode *p, *q, *current;
    p = A->next;
    q = B->next;
    free(B);
    C = A;
    C->next = NULL;
    current = C;
    while (p != NULL && q != NULL)
    {
        if (p->data <= q->data)
        {
            current->next = p;
            p = p->next;
            current = current->next;
        }
        else
        {
            current->next = q;
            q = q->next;
            current = current->next;
        }
    }
    current->next = NULL;
    if (p != NULL)
    {
        current->next = p;
    }
    if (q != NULL)
    {
        current->next = q;
    }
}

int main()
{
    LNode *L1, *L2,*L3;
    printf("请输入第1个链表:\n");
    L1 = Create();
    printf("\n请输入第2个链表:\n");
    L2 = Create();
    Merge(L1, L2, L3);
    printf("合并后的链表为:\n");
    List(L3);
    system("pause");
    return 0;
}

这里写图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值