-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmergeTwoLists.h
More file actions
103 lines (88 loc) · 2.61 KB
/
mergeTwoLists.h
File metadata and controls
103 lines (88 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// mergeTwoLists.h
// linkedList
//
// Created by junl on 2019/7/17.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef mergeTwoLists_hpp
#define mergeTwoLists_hpp
#include "singlyLinkedList.h"
#include <iostream>
namespace leetcode {
/*
21.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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
#pragma mark - 迭代实现
ListNode* mergeTwoLists(ListNode *l1, ListNode*l2){
ListNode *head = new ListNode(0);
ListNode *ct = head;
while (l1 && l2) {
ListNode *node;
if (l1->val < l2->val) {
node = l1;
l1 = l1->next;
}else{
node = l2;
l2 = l2->next;
}
ct->next = node;
ct = node;
}
ListNode *lave = l1 ? l1 : l2;
ct->next = lave;
return head->next;
}
ListNode *mergeTwoLists01(ListNode* head1, ListNode* head2){
ListNode *p1 = head1, *p2=head2;
ListNode dummy(0);
dummy.next = p1;
ListNode *prev = &dummy;
while(p1 && p2){
if(p1->val < p2->val){
prev = p1;
p1 = p1->next;
}else{
prev->next = p2;
p2 = p2->next;
prev = prev->next;
prev->next = p1;
}
}
if (p2){
prev->next = p2;
}
return dummy.next;
}
#pragma mark - 递归实现
ListNode* mergeTwoListsRecursion( ListNode* l1, ListNode* l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *pHead = NULL;
if (l1->val < l2->val){
pHead = l1;
pHead->next = mergeTwoLists(l1->next, l2);
}else{
pHead = l2;
pHead->next = mergeTwoLists(l1, l2->next);
}
return pHead;
}
void test_mergeTwoLists(){
singlyLinkedList ll,l2;
ll.insertTail(1);
ll.insertTail(2);
ll.insertTail(4);
l2.insertTail(1);
l2.insertTail(3);
l2.insertTail(4);
mergeTwoLists01(ll.start(), l2.start())->print();
}
}
#endif /* mergeTwoLists_hpp */