实现的是2个有序链表按升序排,修改了合并处的代码
#include <stdio.h>
#include <stdlib.h>
struct circle{
int ID;
char name;
struct circle* next;
};
int main() {
struct circle* head = (struct circle*) malloc(sizeof(struct circle));
head->next=NULL;
struct circle* p;
p = head;
int n;
printf("请输入表长:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
struct circle* s = (struct circle*) malloc(sizeof(struct circle));
p->next = s;
printf("请输入ID: ");
scanf("%d", &(s->ID));
printf("请输入name: ");
getchar();
scanf("%c", &(s->name));
s->next = NULL;
p = s;
}
p = head;
struct circle* head1 = (struct circle*) malloc(sizeof(struct circle));
head1->next=NULL;
struct circle* p1;
p1 = head1;
int k;
printf("请输入表长:");
scanf("%d", &k);
for (int i = 1; i <= k; i++) {
struct circle* s = (struct circle*) malloc(sizeof(struct circle));
p1->next = s;
printf("请输入ID: ");
scanf("%d", &(s->ID));
printf("请输入name: ");
getchar();
scanf("%c", &(s->name));
s->next = NULL;
p1 = s;
}
p1 = head1;
struct circle* head2 = (struct circle*) malloc(sizeof(struct circle));
head2->next=NULL;
struct circle* p2;
p2 = head2;
p = p->next;
p1 = p1->next;
while(p != NULL || p1 != NULL) {
if (p1 == NULL || (p != NULL && p->ID < p1->ID)) {
p2->next = p;
p2 = p;
p = p->next;
} else {
p2->next = p1;
p2 = p1;
p1 = p1->next;
}
}
p2 = head2;
printf("输出:");
for (int i = 0; i < n+k; i++) {
p2 = p2->next;
printf("%d %c ", (p2->ID), (p2->name));
}
}
可以先自己手动模拟一下例子,然后再用debug一步一步调试,这题大体上就分为3个模块,输入,合并,输出,每个模块依次调试,调试时注意变量的变化。
无序链表合并,修改如下,供参考:
#include <stdio.h>
#include <stdlib.h>
struct circle{
int ID;
char name;
struct circle* next;
};
int main()
{
int n ,i;
struct circle *p = NULL, *head = (struct circle *)malloc(sizeof(struct circle));
head->next = NULL;
p = head;
printf("请输入表长:");
scanf("%d", &n);
for (i = 0;i < n; i++)
{
struct circle *s = (struct circle *)malloc(sizeof(struct circle));
s->next = NULL; // 修改
printf("请输入ID:");
scanf("%d", &s->ID);
printf("请输入name:");
scanf(" %c", &s->name);// 修改
p->next = s; // 修改
p = s; // 修改
}
struct circle *p1 = NULL, *head1 = (struct circle *)malloc(sizeof(struct circle));
head1->next = NULL;
p1 = head1;
printf("请输入表长:");
scanf("%d", &n);
for (i = 0;i < n; i++)
{
struct circle *s = (struct circle *)malloc(sizeof(struct circle));
s->next = NULL; // 修改
printf("请输入ID:");
scanf("%d", &s->ID);
printf("请输入name:");
scanf(" %c", &s->name);// 修改
p1->next = s; // 修改
p1 = s; // 修改
}
struct circle *p2 = NULL, *pt = NULL; // 修改
p = head->next; p1 = head1->next;
head->next = NULL; // 修改
while (1) // 修改
{
if (p)
{
pt = p;
p = p->next;
pt->next = NULL;
}
else if (p1){
pt = p1;
p1 = p1->next;
pt->next = NULL;
}
if (!head->next)
head->next = pt;
else{
p2 = head;
while (p2->next && p2->next->ID > pt->ID)//学号降序
p2 = p2->next;
pt->next = p2->next;
p2->next = pt;
}
if (!p && !p1) break; // 修改
}
free(head1); // 修改
printf("输出:");
for (p2 = head->next;p2;p2 = p2->next)// 修改
printf("%d %c ",p2->ID,p2->name);
return 0;
}