欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > hot100--day2

hot100--day2

2025/5/1 7:48:34 来源:https://blog.csdn.net/weixin_45302337/article/details/145693439  浏览:    关键词:hot100--day2

21. 合并两个有序链表 - 力扣(LeetCode)

先比较,将一个链表排完,之后开始对更长的链表剩余部分去追加到新的上面;

所以整体逻辑分成了两个部分

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {ListNode* cur1 = list1;ListNode* cur2 = list2;ListNode* head = new ListNode();auto cur = head;while(cur1 && cur2){if(cur1->val > cur2->val){cur->next = cur2;cur2 = cur2->next;cur = cur->next;}else{cur->next = cur1;cur1 = cur1->next;cur = cur->next;}}while(cur1){cur->next = cur1;cur1 = cur1->next;cur = cur->next;}while(cur2){cur->next = cur2;cur2 = cur2->next;cur = cur->next;}return head->next;}
};

记住这里还是需要一个head来保存最开始的头节点,不然没办法找到返回的节点;

2. 两数相加 - 力扣(LeetCode) 

先创建一个carry作为标记位也就是计算两数的和;

然后根据carry%10得到和的个位数上的值;

并且使用carry/10得到进位的值,并且由于carry都是+=的形式,所以在第二轮中进位会得到使用;

最后返回head->next就得到了相加后的新链表;

注意:1和2链表的判断要分开,因两者不一定一样长;

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* cur1 = l1;ListNode* cur2 = l2;ListNode* head = new ListNode();auto cur = head;int carry = 0;while(cur1 || cur2 || carry){if(cur1){carry+=cur1->val;cur1 = cur1->next;}if(cur2){carry+=cur2->val;cur2 = cur2->next;}cur->next = new ListNode(carry%10);carry /= 10;cur = cur->next;}return head->next;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词