您的位置:首页 > 编程语言 > C语言/C++

Merge Two Sorted Lists(C++)

2015-10-18 10:45 429 查看
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.

Analysis

The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.

C++ Solution

<span style="font-size:14px;">ListNode mergeTwoLists(ListNode L1, ListNode L2){
ListNode p1 = L1;
ListNode P2 = L2;
ListNode fakeHead = new ListNode(0);
ListNode p = fakeHead;
while(p1 != null && p2 != null){
if(p1.val <= P2.val){
p.next = p1;
p1 = p1.next;
}else{
p.next = p2;
p2 = p2.next;
}
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}</span>


Another solution , we use iteration

ListNode mergeTwoLists(ListNode L1, ListNode L2){
if(L1 == NULL)
return L2;
if(L2= NULL)
return L1;
ListNode p1 = L1;
ListNode p2 = L2;
ListNode fakeHead = new ListNode(0);
ListNode  p = fakeHead;
if(p1.val < = p2.val){
p.next = mergeTwoLists(p1.next, p2);
}else{
p.next = mergeTwoLists(p1, p2.next);
}
p = p.next;
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: