1. <?php
    2. Class ListNode {
    3. public $val = 0;
    4. public $next;
    5. public function __construct($val) {
    6. $this->val = $val;
    7. }
    8. }
    9. class Solution {
    10. public function mergeTwoLists(ListNode $l1, ListNode $l2) {
    11. if (!$l1) return $l2;
    12. if (!$l2) return $l1;
    13. $dummyHead = new ListNode(0);
    14. $current = $dummyHead;
    15. while ($l1 || $l2) {
    16. if (!$l1) {
    17. $current->next = $l2;
    18. break;
    19. }
    20. if (!$l2) {
    21. $current->next = $l1;
    22. break;
    23. }
    24. if ($l1->val < $l2->val) {
    25. $current->next = $l1;
    26. $current = $current->next;
    27. $l1 = $l1->next;
    28. } else {
    29. $current->next = $l2;
    30. $current = $current->next;
    31. $l2 = $l2->next;
    32. }
    33. }
    34. return $dummyHead->next;
    35. }
    36. }
    37. $l1 = new ListNode(1);
    38. $l1->next = new ListNode(2);
    39. $l1->next->next = new ListNode(4);
    40. $l2 = new ListNode(1);
    41. $l2->next = new ListNode(3);
    42. $l2->next->next = new ListNode(4);
    43. $cls = new Solution();
    44. $r = $cls->mergeTwoLists($l1, $l2);
    45. print_r($r);