您的位置:首页 > 其它

Leetcode 21. Merge Two Sorted Lists

2018-01-30 09:58 477 查看
原题:
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




解决方法:


当两个列表都不为空时,每次只将小的添加到新的列表末尾。然后如果某一个列表还剩下一些数据,直接将这些数据加到新的列表末尾即可。

代码:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(INT_MIN);
ListNode* cur = &dummy;
while(l1 && l2){
if (l1->val < l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode