关于#链表#的问题,如何解决?

已有a、b两个链表,每个链表中的结点包括学好、成绩。
要求把两个链表合并,按学号升序排列。
输入
第一行,a、b两个链表元素的数量N、M,用空格隔开。
接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成
输出
按照学号升序排列的数据
样例输入
2 3
5 100
6 89
3 82
4 95
2 10
样例输出
2 10
3 82
4 95
5 100
6 89

我的输出总是会多一行是为甚么
#include 
#include 

struct stu {
    int ID;
    int Score;
};

struct Node {
    struct stu Data;
    struct Node *next;
};

struct Node *CreatList() {
    struct Node *HeadNode = (struct Node *)malloc(sizeof(struct Node));
    HeadNode->next = NULL;
    return HeadNode;
}

struct Node *CreatNode(struct stu Data) {
    struct Node *NewNode = (struct Node *)malloc(sizeof(struct Node));
    NewNode->Data = Data;
    NewNode->next = NULL;
    return NewNode;
}

void InsertByHead(struct Node *HeadNode, struct stu Data) {
    struct Node *NewNode = CreatNode(Data);
    NewNode->next = HeadNode->next;
    HeadNode->next = NewNode;
}

void Combine(struct Node *List1, struct Node *List2) {
    struct Node *HeadNode = List1;
    while (HeadNode->next) {
        HeadNode = HeadNode->next;
    }
    HeadNode->next = List2;
}

void Sort(struct Node *List) {
    struct Node *i = List->next;
    struct Node *j = List->next;
    int temp;
    while (i->next) {
        while (j && j->next) {
            if (j->Data.ID > j->next->Data.ID) {
                temp = j->Data.ID;
                j->Data.ID = j->next->Data.ID;
                j->next->Data.ID = temp;
                temp = j->Data.Score;
                j->Data.Score = j->next->Data.Score;
                j->next->Data.Score = temp;
            }
            j = j->next;
        }
        i = i->next;
        j = List->next;
    }
}

void Print(struct Node *List) {
    struct Node *pMove = List->next;
    while (pMove) {
        printf("%d %d\n", pMove->Data.ID, pMove->Data.Score);
        pMove = pMove->next;
    }
}

int main() {
    int i, n, m;
    struct Node *List1 = CreatList();
    struct Node *List2 = CreatList();
    struct stu info;
    scanf("%d%d", &n, &m);
    for (i = 0; i < n; i++) {
        scanf("%d%d", &info.ID, &info.Score);
        InsertByHead(List1, info);
    }
    for (i = 0; i < m; i++) {
        scanf("%d%d", &info.ID, &info.Score);
        InsertByHead(List2, info);
    }
    Combine(List1, List2);
    Sort(List1);
    Print(List1);
    return 0;
}

你创建的带有头节点的链表 连接两个链表时把第二个链表的头结点连接进来了
HeadNode->next = List2->next;
这才是第一个数据

该回答引用GPTᴼᴾᴱᴺᴬᴵ
你的程序多输出一行的原因可能是由于你在 Print 函数中输出了一个多余的换行符,导致在输出最后一行数据时,多输出了一行空行。可以尝试将 printf("%d %d\n", pMove->Data.ID, pMove->Data.Score); 改为 printf("%d %d", pMove->Data.ID, pMove->Data.Score);,这样就不会输出多余的换行符了。

另外,你的排序算法似乎存在问题,可能无法正确地按照学号升序排列。建议使用更为稳定的排序算法,比如归并排序或快速排序。

上面代码会多输出一组数据