Merge Two Sorted Lists(C++)
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.
/**
* definition for singly-linked list.
* struct listnode {
* int val;
* listnode *next;
* listnode(int x) : val(x), next(null) {}
* };
*/
class solution {
public:
listnode* mergetwolists(listnode* l1, listnode* l2)
{
if(l1==null)
return l2;
if(l2==null)
return l1;
listnode* result=new listnode(0);
listnode* cur=result;
while(l1!=null&&l2!=null)
{
if(l1->val
{
cur->next=l1;
l1=l1->next;
}
else
{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
while(l1==null&&l2!=null)
{
cur->next=l2;
l2=l2->next;
cur=cur->next;
}
while(l2==null&&l1!=null)
{
cur->next=l1;
l1=l1->next;
cur=cur->next;
}
return result->next;
}
};
推荐阅读
-
LeetCode C++ 599. Minimum Index Sum of Two Lists【Hash Table】简单
-
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
-
[LeetCode]Merge Two Sorted Lists(Python)
-
1.Merge Two Sorted Arrays. py/合并排序有序数列
-
Median of Two Sorted Arrays(C++)
-
Leetcode【121】 Merge Two Sorted Lists(Java版)-附测试代码
-
Leetcode No.88 Merge Sorted Array(c++实现)
-
21. Merge Two Sorted Lists
-
Merge K Sorted List Leetcode #23 题解[C++]
-
Median of Two Sorted Arrays Leetcode #4 题解[C++]