给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
指针向后遍历相加就可以了,主要是注意进位。
增加一个哨兵节点指向后面生成的节点。
php代码:
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers($l1, $l2) {
$list = new ListNode();
$this->getSumList($l1,$l2,$list);
return $list->next;
}
function getSumList($l1,$l2,$list,$add=0){
if($l1 === null && $l2 === null && $add ==0){
return $list;
}
$tmp = $l1->val+$l2->val+$add;
$tmp_list = new ListNode($tmp%10);
$list->next = $tmp_list;
$l1 = $l1->next;
$l2 = $l2->next;
return $this->getSumList($l1,$l2,$tmp_list,$tmp>=10?1:0);
}
}
go代码:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
list := &ListNode{}
newList := list
tmp := 0
for l1 != nil || l2 != nil || tmp !=0{
if l1 != nil {
tmp += l1.Val
l1 = l1.Next
}
if l2 != nil{
tmp += l2.Val
l2 = l2.Next
}
tmpList := &ListNode{tmp%10,nil}
newList.Next = tmpList
tmp = tmp/10
newList = newList.Next
}
return list.Next
}
标签:tmp,ListNode,list,next,l2,l1,GO,PHP,两数
来源: https://blog.csdn.net/wyisgoodman/article/details/114139994