给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
示例:
输入:(0->2 -> 4 ->0-> 3) + (0->5 -> 6 -> 8)
输出:0->7->0->9->3
原因:30420 + 8650 = 39070
class Node
{
public $val = null;
public $next = null ;
public function __construct($val)
{
$this->val = $val;
}
}
function arrToList($arr){
$head = null;
$count = count($arr);
$i = 0;
while($i < $count ){
$new = new Node($arr[$i]);
if(empty($head)){
$head = $new;
$now = $head;
}
$now->next = $new;
$now = $now->next;
$i++;
}
return $head;
}
function addList($l1, $l2){
$t = $l1;
$k = 0;
do{
$val = $t->val + $l2->val + $k;
$t->val = $val % 10;
$k = $val >= 10 ? 1 : 0;
if (!$l2->next && !$t->next && $k) {
$t->next = new Node(1);
break;
}
if ($t->next && !$l2->next) {
$l2->next = new Node(0);
}
if ($l2->next && !$t->next) {
$t->next = new Node(0);
}
$t = $t->next;
$l2 = $l2->next;
}while ($t);
return $l1;
}
$arr1 = [0, 2, 4, 0, 3];
$arr2 = [0, 5, 6, 8];
$l1 = arrToList($arr1);
$l2 = arrToList($arr2);
print_r($l1);
print_r($l2);
print_r(addList($l1, $l2));
[Running] php "/Users/why/Desktop/php/why.php"
Node Object
(
[val] => 0
[next] => Node Object
(
[val] => 2
[next] => Node Object
(
[val] => 4
[next] => Node Object
(
[val] => 0
[next] => Node Object
(
[val] => 3
[next] =>
)
)
)
)
)
Node Object
(
[val] => 0
[next] => Node Object
(
[val] => 5
[next] => Node Object
(
[val] => 6
[next] => Node Object
(
[val] => 8
[next] =>
)
)
)
)
Node Object
(
[val] => 0
[next] => Node Object
(
[val] => 7
[next] => Node Object
(
[val] => 0
[next] => Node Object
(
[val] => 9
[next] => Node Object
(
[val] => 3
[next] =>
)
)
)
)
)
[Done] exited with code=0 in 0.231 seconds
解法原理:对象浅拷贝不会改变原对象的属性值,代码中$t->val是通过地址改变的l1链表的值。