Wwerday 2022-04-10 17:24 采纳率: 100%
浏览 24
已结题

两个有序链表的归并,然后逆序输出,输出的答案总多一个


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

typedef struct node{
    int data;
    struct node* next;

}Node;

void CreatList(Node* head, int n){
    Node* p;
    p = (Node*)malloc(sizeof(Node));
    p = head;

    for(int i=0; i<n; i++){
        p->next = (Node*)malloc(sizeof(Node));
        scanf("%d", &p->next->data);
        p = p->next;
    }
    p->next = NULL;
}

Node* SortList(Node* head1, Node* head2){
    Node *head, *p1, *p2, *p;
    p1 = head1->next;
    p2 = head2->next;
    head = (Node*)malloc(sizeof(Node));
    head->next = NULL;
    p = head;

    while (p1 != NULL && p2 != NULL){
        if(p1->data >= p2->data){
            p->next = p2;
            p = p->next;
            p2 = p2->next;
        }
        else{
            p->next = p1;
            p = p->next;
            p1 = p1->next;
        }
    }
    if(p1 == NULL){
        p->next = p2;
    }
    else if(p2 == NULL){
        p->next = p1;
    }
    return head;
}

void Print(Node* head){
    if(head == NULL){
        return;
    }
    Print(head->next);
    printf("%d ",head->data);
}

int main()
{
    Node *head1, *head2, *head;
    int m,n;
    scanf("%d%d",&m, &n);
    head1 = (Node*)malloc(sizeof(Node));
    head2 = (Node*)malloc(sizeof(Node));
    CreatList(head1, m);
    CreatList(head2, n);
    head = SortList(head1,head2);
    Print(head);
    return 0;
}

  • 写回答

2条回答 默认 最新

  • 关注

    改成下面这样子试试?

    int main()
    {
        Node *head1, *head2, *head;
        int m,n;
        scanf("%d%d",&m, &n);
        head1 = (Node*)malloc(sizeof(Node));
        head2 = (Node*)malloc(sizeof(Node));
        CreatList(head1, m);
        CreatList(head2, n);
        head = SortList(head1,head2);
        Print(head->next);
        return 0;
    }
    

    或者在SortList中return head->next
    也可以在Print中修改

    你头节点没有用到,但打印出来了
    如果对你有帮助,望采纳

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月18日
  • 已采纳回答 4月10日
  • 创建了问题 4月10日

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重