#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;
}
两个有序链表的归并,然后逆序输出,输出的答案总多一个
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 绿豆蛙给生活加点甜 2022-04-10 18:26关注
改成下面这样子试试?
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无用
悬赏问题
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
- ¥15 机器人轨迹规划相关问题
- ¥15 word样式右侧翻页键消失