如何将两个升序链表合并为一个降序链表?
算法的时间复杂度要求O(n),空间复杂度要求O(1).
C语言实现。
如何将两个升序链表合并为一个降序链表?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- 广大菜鸟 2022-03-11 17:09关注
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int value; struct Node*next; }Node; Node*function(Node*t1,Node*t2){ Node*head=(Node*)malloc(sizeof(Node)); head->next=NULL; Node*p,*q; p=t1,q=t2; while(p!=NULL&q!=NULL){ Node*tmp=(Node*)malloc(sizeof(Node)); if(p->value<q->value){ tmp->value=p->value; p=p->next; }else{ tmp->value=q->value; q=q->next; } tmp->next=head->next; head->next=tmp; } while(p!=NULL){ Node*tmp=(Node*)malloc(sizeof(Node)); tmp->value=p->value; tmp->next=head->next; head->next=tmp; p=p->next; } while(q!=NULL){ Node*tmp=(Node*)malloc(sizeof(Node)); tmp->value=q->value; tmp->next=head->next; head->next=tmp; q=q->next; } return head->next; } int main(){ //1-3-5 Node*t=(Node*)malloc(sizeof(Node));t->value=1; t->next=(Node*)malloc(sizeof(Node));t->next->value=3; t->next->next=(Node*)malloc(sizeof(Node));t->next->next->value=5; t->next->next->next=NULL; //2-4-6 Node*t1=(Node*)malloc(sizeof(Node));t1->value=2; t1->next=(Node*)malloc(sizeof(Node));t1->next->value=4; t1->next->next=(Node*)malloc(sizeof(Node));t1->next->next->value=6; t1->next->next->next=NULL; Node*result=function(t,t1); Node*p=result; while(p!=NULL){ printf("%d\t",p->value); p=p->next; } system("pause"); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 3无用
悬赏问题
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 ubuntu子系统密码忘记
- ¥15 保护模式-系统加载-段寄存器