一道c语言的题目,和链表的排序有关,我做了,始终调试不成功,求大神帮忙做一下!!!!

2025-03-26 10:36:07
推荐回答(1个)
回答1:

#include 
#include 

#define LEN sizeof(struct student)

/* User Code Begin */
struct student {
int num;
int score;
struct student *next;
};

struct student *getEmptyList();
void createList(struct student *head);
struct student *mergeLists(struct student *ah, struct student *bh);
void print(struct student *head);
void sortList(struct student *head); // 冒泡排序

/* User Code End(考生添加代码结束) */

/* print以规定的格式完成遍历显示指定的链表 */
void printList(struct student *Head);

int main(void) {
struct student *ah = getEmptyList();
struct student *bh = getEmptyList();
struct student *ch;
printf("创建链表A,请输入学号及成绩(均输入为0时表示停止):\n");
createList(ah);
printf("\n创建链表B,请输入学号及成绩(均输入为0时表示停止):\n");
createList(bh);

printf("\n链表A\n");
print(ah);
printf("\n链表B\n");
print(bh);

ch = mergeLists(ah,bh);
sortList(ch);
printf("\n链表C\n");
print(ch);

return 0;
}

void print(struct student *head) {
struct student *p = head->next;
while(p) {
printf("%d\t%d\n", p->num, p->score);
p = p->next;
}
printf("\t");
}

struct student *getEmptyList() {
struct student *head = (struct student *)malloc(LEN);
head->next = 0;
return head;
}

/* User Code Begin(考生在此后完成自定义函数的设计,行数不限) */
void createList(struct student *head) {
int num, score;
struct student *p = head;
printf("学号 成绩(0 0 结束):");
while(scanf("%d%d", &num, &score) == 2) {
if(num == 0 && score == 0) break;
p->next = (struct student *)malloc(LEN);
p->next->num = num;
p->next->score = score;
p = p->next;
printf("学号 成绩(0 0 结束):");
}
p->next = NULL;
}

struct student *mergeLists(struct student *ah, struct student *bh) {
struct student *p,*newnode;
struct student *hc = getEmptyList();
for(p = ah->next; p; p = p->next) { // 先复制ha
newnode = (struct student *)malloc(LEN);
*newnode = *p;
newnode->next = hc->next; // 头插法
hc->next = newnode;
}
for(p = bh->next; p; p = p->next) { // 再复制hb
newnode = (struct student *)malloc(LEN);
*newnode = *p;
newnode->next = hc->next;
hc->next = newnode;
}
return hc;
}

void sortList(struct student *head) { // 冒泡排序
struct student *p,*q,*pt;
p = head;
while(p->next) {
q = p->next;
while(q->next) {
if(p->next->num > q->next->num) {
pt = p->next;
p->next = q->next;
q->next = q->next->next;
p->next->next = pt;
}
else q = q->next;
}
p = p->next;
}
}