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


#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;
}

改成下面这样子试试?

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中修改

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

我的测试输入:2,2,1,5,8,9
断点调试:第一次进入的时候你的第一个节点的值被自动初始化了一个无效值,接下来的其余值被依次赋值
结论:由于第一个节点被赋予了无效值,逆序打印就会多一个值
断点截图:

img