Skip to content

Commit 26efc66

Browse files
authored
Create MergeTwoSortedLists.php
1 parent 18849bb commit 26efc66

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Easy/MergeTwoSortedLists.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
}

0 commit comments

Comments
 (0)