题目
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
这里学习了来自网络leetcode里面的算法题
//php演示链表需要定义node节点
class listNode
{
public $val = 0;
public $next = null;
function __construct ($val) {
$this->val = $val;
}
}
class solution
{
function addTwoNumbers ($l1, $l2) {
$add = 0;
$list = new listNode(0);
$cur = $list;
while ($l1 || $l2) {
$x = $l1 != null ? $l1->val : 0;
$y = $l2 != null ? $l2->val : 0;
$val = ($x + $y + $add)%10;
$add = ($x + $y + $add)/10;
$new = new listNode($val);
$cur->next = $new;
$cur = $cur->next;
if ($l1 != null) {
$l1 = $l1->next;
}
if ($l2 != null) {
$l2 = $l2->next;
}
}
if ($add > 0) {
$cur->next = new listNode($add);
}
return $list->next;
}
}