谁能帮我把输出链表改为递增的

#include <stdio.h>
#include <stdlib.h>

// 定义单链表结点结构
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 子函数2:输出单链表所有元素
void printLinkedList(Node* head) {
    if (head == NULL) {
        printf("链表为空\n");
        return;
    }

    Node* p = head;
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

// 子函数3:教材P31算法2.12 - 归并两个非递减排列的单链表la和lb,结果存放在lc中
Node* mergeLinkedLists(Node* la, Node* lb) {
    if (la == NULL) {
        return lb;
    } else if (lb == NULL) {
        return la;
    }

    Node* lc;  // 新建链表lc
    Node* tail;  // lc的尾指针

// 初始化lc
    if (la->data <= lb->data) {
        lc = lb;
        lb = lb->next;
    } else {
        lc = la;
        la = la->next;
    }
    tail = lc;

    // 合并la和lb
    while (la != NULL && lb != NULL) {
        if (la->data <= lb->data) {
            tail->next = lb;
            lb = lb->next;
        } else {
            tail->next = la;
            la = la->next;
        }
        tail = tail->next;
    }

    // 将剩余的结点连接到lc的末尾
    if (la != NULL) {
        tail->next = la;
    } else {
        tail->next = lb;
    }

    return lc;
}

int main() {
    // 建立链表La
    Node* La = NULL;  // La的头指针
    int n, x;
    printf("请输入链表La的元素个数: ");
    scanf("%d", &n);
    printf("请输入链表La的%d个元素值(非递减排列):", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);

        // 创建新结点
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = x;
        newNode->next = La;

        // 更新La的头指针
        La = newNode;
    }
    printf("链表La的元素为:");
    printLinkedList(La);

    // 建立链表Lb
    Node* Lb = NULL;  // Lb的头指针
    printf("请输入链表Lb的元素个数: ");
    scanf("%d", &n);
    printf("请输入链表Lb的%d个元素值(非递减排列):", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);

        // 创建新结点
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = x;
        newNode->next = Lb;

        // 更新Lb的头指针
        Lb = newNode;
    }
    printf("链表Lb的元素为:");
    printLinkedList(Lb);

    // 归并

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值