归并两个有序链表

系列文章目录

前言

《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
4.2节,page120,习题6

一、题目描述

令x=(x1,x2,…,xn)和y=(y1,y2,…ym)是两个链表,按数据域的非递减序排列。构造算法归并这两个链表,结果存储在新链表z中,z也按数据域的非递减序排列。在归并过程,表x和表y中的结点一一链到z中,要求不用临时结点。讨论算法的复杂度。

二、c++代码

代码如下:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef struct Node{
    int data;
    struct Node *link;
}listNode;

listNode* create_list(int length)
{
    if(length<1)
    {
        printf("链表中没有元素!\n");
    }
    listNode *first = (listNode*)malloc(sizeof(listNode));
    first->link = NULL;
    listNode *p = first;
    int value;
    printf("请输入%d个整数:\n",length);
    for(int i=1;i<=length;i++)
    {
        listNode *temp = (listNode*)malloc(sizeof(listNode));
        scanf("%d",&value);
        temp->data = value;
        p->link=temp;
        p = temp;
    }
    p->link = NULL;
    return first;
};

listNode* merge_list(listNode *l1,listNode *l2)
{
    listNode *new_list = new listNode;
    new_list->link = NULL;
    listNode *temp = new_list;
    listNode *temp1 = l1->link;
    listNode *temp2 = l2->link;
    while (temp1 && temp2)
    {
        if(temp1->data < temp2->data)
        {
            listNode *p = new listNode;
            p->data = temp1->data;
            temp1 = temp1->link;
            temp->link = p;
        } else{
            listNode *p = new listNode;
            p->data = temp2->data;
            temp2 = temp2->link;
            temp->link = p;
        }
        temp = temp->link;
    }
    while (temp1)
    {
        listNode *p = new listNode;
        p->data = temp1->data;
        temp->link = p;
        temp1 = temp1->link;
        temp = temp->link;
    }
    while (temp2)
    {
        listNode *p = new listNode;
        p->data = temp2->data;
        temp->link = p;
        temp2 = temp2->link;
        temp = temp->link;
    }
    return new_list;
}

void print_list(listNode* list)
{
    listNode *tmp;
    tmp = list->link;
    if(tmp==NULL) {
        printf("链表中没有元素!\n");
        return;
    }
    while (tmp)
    {
        printf("%2d",tmp->data);
        tmp = tmp->link;
    }
}

int main() {
    listNode *x,*y,*z;
    int len1,len2;
    printf("输入链表1的长度:");
    scanf("%d",&len1);
    printf("输入链表2的长度:");
    scanf("%d",&len2);
    x = create_list(len1);
    y = create_list(len2);
    z = merge_list(x,y);
    printf("合并之后的链表为:\n");
    print_list(z);
    return 0;
}

总结

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值