<?php/** * Class ListNode * 链表 */Class ListNode { public $val = 0; public $next; public function __construct($val) { $this->val = $val; }}/** * (2->4->2) * + * (5->6->7) * = * (7->0->0->1) * */Class Solution { public function addTwoNum(ListNode $n1, ListNode $n2) { $add = 0; $list = new ListNode(0); $cur = $list; while ($n1 || $n2) { $x = ($n1 != null) ? $n1->val : 0; $y = ($n2 != null) ? $n2->val : 0; $val = ($x + $y + $add) % 10; $add = floor(($x + $y + $add) / 10); $new = new ListNode($val); $cur->next = $new; $cur = $cur->next; if ($n1 != null) { $n1 = $n1->next; } if ($n2 != null) { $n2 = $n2->next; } } if ($add > 0) { $cur->next = new ListNode($add); } return $list->next; }}$n1 = new ListNode(2);$n1->next = new ListNode(4);$n1->next->next = new ListNode(2);$n2 = new ListNode(5);$n2->next = new ListNode(6);$n2->next->next = new ListNode(7);// 加$cls = new Solution();$ret = $cls->addTwoNum($n1, $n2);