难度: 中等php
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.html
You may assume the two numbers do not contain any leading zero, except the number 0 itself.node
给出两个 非空
的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序
的方式存储的,而且它们的每一个节点只能存储 一位 数字。
若是,咱们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您能够假设除了数字 0 以外,这两个数都不会以 0 开头。git
示例:this
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
缘由:342 + 465 = 807
spa
这个题目至关因而两个链表进行相加,把链表每一节点的值存到新链表对应的节点,涉及到进位。3d
/** * 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; } }
运行结果: code
PHP链表打印出来的结构:htm
ListNode Object ( [val] => 0 [next] => ListNode Object ( [val] => 7 [next] => ListNode Object ( [val] => 0 [next] => ListNode Object ( [val] => 8 [next] => ) ) ) )
连接:https://leetcode-cn.com/problems/add-two-numbers/blog
一、PHP 链表的使用 - 简书
https://www.jianshu.com/p/e409ec512caa 二、2. Add Two Numbers · leetcode https://leetcode.wang/leetCode-2-Add-Two-Numbers.html