没有合适的资源?快使用搜索试试~ 我知道了~
LeetCode Merge 2 Sorted Lists解决方案
需积分: 0 0 下载量 175 浏览量
2024-01-23
23:14:22
上传
评论
收藏 11KB DOCX 举报
温馨提示
试读
1页
LeetCode Merge 2 Sorted Lists解决方案
资源推荐
资源详情
资源评论
Summary:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing
together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
~~~
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL && l2 == NULL) return NULL;
else if (l1 != NULL && l2 == NULL) return l1;
else if (l1 == NULL && l2 != NULL) return l2;
ListNode *temp1, *temp2, *result;
temp1 = l1->val <= l2->val ? l1 : l2;
temp2 = l1->val <= l2->val ? l2 : l1;
result = temp1;
while (temp2 != NULL) {
if (temp1->next == NULL) {
temp1->next = temp2;
break;
}
if (temp2->val >= temp1->val && temp2->val <= temp1->next->val) {
ListNode *i = new ListNode(temp2->val);
i->next = temp1->next;
temp1->next = i;
temp1 = temp1->next;
temp2 = temp2->next;
}
else
{
temp1 = temp1->next;
}
}
return result;
}
~~~
资源评论
句号(在IT行业摸爬滚打)
- 粉丝: 278
- 资源: 28
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功