难度: 中等
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.
给出两个?非空
的链表用来表示两个非负的整数。其中,它们各自的位数是按照?逆序
?的方式存储的,并且它们的每个节点只能存储?一位?数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0?开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
这个题目相当于是两个链表进行相加,把链表每一节点的值存到新链表对应的节点,涉及到进位。
/**
* 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 = null;
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);
if (is_null($result_list)){
$result_list = $tmp_list;
} else{
$current_node = $result_list;
while ($current_node->next !== null) {
$current_node = $current_node->next;
}
$current_node->next = $tmp_list;
// $next->next = $tmp_list; //?
}
// $next = $tmp_list; //?
$l1 = $l1->next;
$l2 = $l2->next;
} while ($l1 || $l2 || $add_flag);
return $result_list;
}
}
运行结果:
PHP链表打印出来的结构:
ListNode Object
(
[val] => 2
[next] => ListNode Object
(
[val] => 4
[next] => ListNode Object
(
[val] => 1
[next] => ListNode Object
(
[val] => 1
[next] =>
)
)
)
)
需要注意的是对链接新增节点不能直接使用:
$result_list->next = $tmp_list;
这样赋值的话$result_list
链表最终只有2个节点:最开始的节点和末尾节点,中间的节点被覆盖了。
链接:https://leetcode-cn.com/problems/add-two-numbers/
1、PHP 链表的使用 - 简书
https://www.jianshu.com/p/e409ec512caa
原文:https://www.cnblogs.com/52fhy/p/11031865.html