File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *mergeTwoLists (ListNode *l1, ListNode *l2) {
12
+ // Start typing your C/C++ solution below
13
+ // DO NOT write int main() function
14
+
15
+ ListNode prev_head (0 );
16
+ ListNode *sorted_list = &prev_head;
17
+
18
+ while (l1 && l2) {
19
+ if (l1->val < l2->val ) {
20
+ sorted_list->next = l1;
21
+ l1 = l1->next ;
22
+ sorted_list = sorted_list->next ;
23
+ }
24
+ else {
25
+ sorted_list->next = l2;
26
+ l2 = l2->next ;
27
+ sorted_list = sorted_list->next ;
28
+ }
29
+ }
30
+
31
+ while (l1) {
32
+ sorted_list->next = l1;
33
+ l1 = l1->next ;
34
+ sorted_list = sorted_list->next ;
35
+ }
36
+ while (l2) {
37
+ sorted_list->next = l2;
38
+ l2 = l2->next ;
39
+ sorted_list = sorted_list->next ;
40
+ }
41
+ return prev_head.next ;
42
+ }
43
+ };
You can’t perform that action at this time.
0 commit comments