File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ <?php
3
+
4
+ /**
5
+ * Definition for a singly-linked list.
6
+ * class ListNode {
7
+ * public $val = 0;
8
+ * public $next = null;
9
+ * function __construct($val = 0, $next = null) {
10
+ * $this->val = $val;
11
+ * $this->next = $next;
12
+ * }
13
+ * }
14
+ */
15
+ class Solution {
16
+
17
+ /**
18
+ * @param ListNode $list1
19
+ * @param ListNode $list2
20
+ * @return ListNode
21
+ */
22
+ function mergeTwoLists ($ list1 , $ list2 ) {
23
+ $ dummy = new ListNode ();
24
+ $ current = $ dummy ;
25
+
26
+ if ($ list1 === null ) return $ list2 ;
27
+ if ($ list2 === null ) return $ list1 ;
28
+
29
+ $ this ->merge ($ list1 , $ list2 , $ current );
30
+
31
+ return $ dummy ->next ;
32
+ }
33
+
34
+ function merge ($ head1 , $ head2 , &$ mergedList ) {
35
+ if ($ head1 === null ) {
36
+ $ mergedList ->next = $ head2 ;
37
+ return ;
38
+ }
39
+ if ($ head2 === null ) {
40
+ $ mergedList ->next = $ head1 ;
41
+ return ;
42
+ }
43
+
44
+ if ($ head1 ->val <= $ head2 ->val ) {
45
+ $ mergedList ->next = $ head1 ;
46
+ $ mergedList = $ mergedList ->next ;
47
+ $ this ->merge ($ head1 ->next , $ head2 , $ mergedList );
48
+ } else {
49
+ $ mergedList ->next = $ head2 ;
50
+ $ mergedList = $ mergedList ->next ;
51
+ $ this ->merge ($ head1 , $ head2 ->next , $ mergedList );
52
+ }
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments