1. <?php
    2. /**
    3. * Class ListNode
    4. * 链表
    5. */
    6. Class ListNode {
    7. public $val = 0;
    8. public $next;
    9. public function __construct($val) {
    10. $this->val = $val;
    11. }
    12. }
    13. /**
    14. * (2->4->2)
    15. * +
    16. * (5->6->7)
    17. * =
    18. * (7->0->0->1)
    19. *
    20. */
    21. Class Solution {
    22. public function addTwoNum(ListNode $n1, ListNode $n2) {
    23. $add = 0;
    24. $list = new ListNode(0);
    25. $cur = $list;
    26. while ($n1 || $n2) {
    27. $x = ($n1 != null) ? $n1->val : 0;
    28. $y = ($n2 != null) ? $n2->val : 0;
    29. $val = ($x + $y + $add) % 10;
    30. $add = floor(($x + $y + $add) / 10);
    31. $new = new ListNode($val);
    32. $cur->next = $new;
    33. $cur = $cur->next;
    34. if ($n1 != null) {
    35. $n1 = $n1->next;
    36. }
    37. if ($n2 != null) {
    38. $n2 = $n2->next;
    39. }
    40. }
    41. if ($add > 0) {
    42. $cur->next = new ListNode($add);
    43. }
    44. return $list->next;
    45. }
    46. }
    47. $n1 = new ListNode(2);
    48. $n1->next = new ListNode(4);
    49. $n1->next->next = new ListNode(2);
    50. $n2 = new ListNode(5);
    51. $n2->next = new ListNode(6);
    52. $n2->next->next = new ListNode(7);
    53. // 加
    54. $cls = new Solution();
    55. $ret = $cls->addTwoNum($n1, $n2);