已解决
c语言练习91:合并两个有序链表
来自网友在路上 148848提问 提问时间:2023-10-24 04:59:11阅读次数: 48
最佳答案 问答题库488位专家为你答疑解惑
合并两个有序链表
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码1:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){//判断链表是否为空if(list1==NULL){return list2;}if(list2==NULL){return list1;}//走到这里说明链表不为空,遍历链表ListNode*cur1=list1;ListNode*cur2=list2;ListNode*newhead,*newtail;newhead=newtail=NULL;while(cur1&&cur2){//1.空链表的情况下:插入的结点就是链表的头结点和尾结点//2.非空链表:插入的结点是链表的新的尾结点,头结点不变if(cur1->val<cur2->val){if(newhead==NULL){newhead=newtail=cur1;}else{newtail->next=cur1;newtail=newtail->next;}cur1=cur1->next;}else{//cur2<=cur1if(newhead==NULL){newhead=newtail=cur2;}else{newtail->next=cur2;newtail=newtail->next;}cur2=cur2->next;}}if(cur1){newtail->next=cur1;}if(cur2){newtail->next=cur2;}return newhead;
}
优化:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){//判断链表是否为空if(list1==NULL){return list2;}if(list2==NULL){return list1;}//走到这里说明链表不为空,遍历链表ListNode*cur1=list1;ListNode*cur2=list2;ListNode*newhead,*newtail;//newhead为哨兵卫newhead=newtail=(ListNode*)malloc(sizeof(ListNode));// ListNode*newhead,*newtail;// newhead=newtail=NULL;while(cur1&&cur2){//1.空链表的情况下:插入的结点就是链表的头结点和尾结点//2.非空链表:插入的结点是链表的新的尾结点,头结点不变if(cur1->val<cur2->val){// if(newhead==NULL){// newhead=newtail=cur1;// }// else{// newtail->next=cur1;// newtail=newtail->next;// }newtail->next=cur1;newtail=newtail->next;cur1=cur1->next;}else{//cur2<=cur1// if(newhead==NULL){// newhead=newtail=cur2;// }// else{// newtail->next=cur2;// newtail=newtail->next;// }newtail->next=cur2;newtail=newtail->next;cur2=cur2->next;}}if(cur1){newtail->next=cur1;}if(cur2){newtail->next=cur2;}ListNode*returnhead=newhead->next;free(newhead);return returnhead;
}
查看全文
99%的人还看了
相似问题
- 【剑指offer|图解|链表】链表的中间结点 + 链表中倒数第k个结点
- 【数据结构初阶(3)】双向带头结点循环链表
- 单链表相关面试题--4.输入一个链表,输出该链表中倒数第k个结点
- 王道数据结构课后代码题p150 15.设有一棵满二叉树(所有结点值均不同),已知其先序序列为 pre,设计一个算法求其后序序列post。(c语言代码实现)
- 【数据结构】树的基本性质(计算树的总结点数与叶结点数)
- 【数据结构】树与二叉树(五):二叉树的顺序存储(初始化,插入结点,获取父节点、左右子节点等)
- NowCoder | 链表中倒数第k个结点
- 设一棵完全二叉树具有1000个结点,则此完全二叉树有()叶子结点,有()个度为2的结点。
- 11.3递归建二叉树,二叉树函数规范化输入输出,一些二叉树性质,求叶子结点与树的高度
- 二叉树第i层结点个数
猜你感兴趣
版权申明
本文"c语言练习91:合并两个有序链表":http://eshow365.cn/6-23005-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: acwing第 126 场周赛 (扩展字符串)
- 下一篇: Maven 基础教程系列