1
+ /* *
2
+ * @Author: Chacha
3
+ * @Date: 2019-01-06 22:50:09
4
+ * @Last Modified by: Chacha
5
+ * @Last Modified time: 2019-01-06 23:13:13
6
+ */
7
+
8
+ #include < iostream>
9
+ #include < string>
10
+ using namespace std ;
11
+
12
+ /* *
13
+ * Definition for singly-linked list(单向链表)
14
+ * Source: https://zh.wikipedia.org/wiki/链表
15
+ */
16
+ struct ListNode {
17
+ int val;
18
+ ListNode *next;
19
+ ListNode (int x) : val(x), next(NULL ) {}
20
+ };
21
+
22
+ class Solution {
23
+ public:
24
+ /* *
25
+ * Merge two sorted linked lists and return it as a new list.
26
+ * The new list should be made by splicing together the nodes of the first two lists.
27
+ *
28
+ * Example:
29
+ * Given 1->3->8->11->15->null, 2->null
30
+ * return 1->2->3->8->11->15->null
31
+ *
32
+ * Source: https://leetcode.com/problems/merge-two-sorted-lists/
33
+ *
34
+ * Operation steps:
35
+ * 1. Exception handling, included in dummy->next
36
+ * 2. Create the dummy and lastNode nodes, let the lastNode pointed to dummy node
37
+ * 3. Loop processing for non-empty l1, l2, linking the smaller of l1/l2 to lastNode->next, recursing lastNode
38
+ * 4. one of the linked lists in l1/l2 is empty to exit the while loop,
39
+ * and the non-empty list header is linked to lastNode->next
40
+ * 5. Return dummy->next, which is the final head pointer
41
+ */
42
+ ListNode* mergeTwoLists (ListNode* l1, ListNode* l2) {
43
+ ListNode* dummy = new ListNode (0 );
44
+ ListNode* lastNode = dummy;
45
+
46
+ while (l1 != NULL && l2 != NULL ){
47
+
48
+ if (l1->val < l2->val ) {
49
+ lastNode->next = l1;
50
+ l1 = l1->next ;
51
+ } else {
52
+ lastNode->next = l2;
53
+ l2 = l2->next ;
54
+ }
55
+
56
+ lastNode = lastNode->next ;
57
+ }
58
+
59
+ lastNode->next = (l1 != NULL ) ? l1 : l2;
60
+ return dummy->next ;
61
+ }
62
+ };
63
+
64
+ /* Function to print nodes in a given linked list */
65
+ void printList (ListNode *node) {
66
+ while (node != NULL ) {
67
+ printf (" %d " , node->val );
68
+ node = node->next ;
69
+ }
70
+ }
71
+
72
+ int main () {
73
+ ListNode* l1 = new ListNode (1 );
74
+ l1->next = new ListNode (3 );
75
+ l1->next ->next = new ListNode (5 );
76
+ l1->next ->next ->next = new ListNode (7 );
77
+ l1->next ->next ->next ->next = new ListNode (9 );
78
+
79
+ ListNode* l2 = new ListNode (2 );
80
+ l2->next = new ListNode (4 );
81
+ l2->next ->next = new ListNode (6 );
82
+ l2->next ->next ->next = new ListNode (8 );
83
+ l2->next ->next ->next ->next = new ListNode (10 );
84
+
85
+ ListNode* merged = Solution ().mergeTwoLists (l1, l2);
86
+
87
+ printList (merged);
88
+
89
+ return 0 ;
90
+ }
0 commit comments