Leetcode——2. 两数相加

题目

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

PHP

/**
* Definition for a singly-linked list.
* class ListNode {
*     public $val = 0; * public$next = null;
*     function __construct($val) {$this->val = $val; } * } */ class Solution { /** * @param ListNode$l1
* @param ListNode $l2 * @return ListNode */ function addTwoNumbers($l1, $l2) {$add_flag = 0;
$result_list = new ListNode(0);$curr =  $result_list; //指向当前链表 do {$val = $l1->val +$l2->val + $add_flag; if ($val >= 10) {
$add_flag = 1;$val -= 10; //减去，因为进位了
} else {
$add_flag = 0; }$tmp_list = new ListNode($val);$curr->next = $tmp_list;$curr = $curr->next;$l1 = $l1->next;$l2 = $l2->next; } while ($l1 || $l2 ||$add_flag);

return \$result_list->next;
}
}


PHP链表打印出来的结构：

ListNode Object
(
[val] => 0
[next] => ListNode Object
(
[val] => 7
[next] => ListNode Object
(
[val] => 0
[next] => ListNode Object
(
[val] => 8
[next] =>
)

)

)

)



参考

1、PHP 链表的使用 - 简书
https://www.jianshu.com/p/e409ec512caa
2、2. Add Two Numbers · leetcode