问题描述:
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
题目难度: Medium
自我理解:
当时的思路有两种方案:
1、将整个链表转换为数字,然后加法之后进行数字转链表的逆序就OK
2、整个链表直接翻转加
解题历程:
当时看到leetcode给的模板,心里想,算了试试第二种方案来做,当时觉得这个方案比较难实现,从10点40左右开始搞,心里想的是12点前做完,按照方案二做完时间点为11点57分,好歹也算是完成了,但是耗费的时间有点长,实在惭愧啊,害
第一遍书写时想到的临界点时:考虑到两个链表中任意某一个链表过长,需要将长的那部分给拽下来,贴在最后的结果链表后面就OK了
写完直接点击 run code ,然后除过开始的一些语法报错之外,没有大的方向的问题,美滋滋,直接submit,然后才发现自己进入了地狱模式
首先报错的是 两个链表,但是 长度相等,且值都是5
链表1 : [5]
链表2 :[5]
没考虑到这个问题,然后加上,然后next都为null,但是 上一次增加的结果超过10,再给后面增加一个单独1
这个case 过了,但是后续又有一个出错了,
比如:
链表1:[1]
链表2:[9, 9]
也就是说,如果后续的长的那个链表,上一次增加的结果超过10, 需要进1,但是本身自己这个再进1 的话,还是超过了10,那么就仍旧需要给下一位加1,本位置位0,这个是我当时没考虑到的
然后后续经过 一系列的调试,总算是看到了下面的结果,开心呐~
Success
Runtime: 12 ms, faster than 97.76% of PHP online submissions for Add Two Numbers.
Memory Usage: 15 MB, less than 50.00% of PHP online submissions for Add Two Numbers.
直接贴方案二的代码:
/**
* 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) {
if(!$l1 || !$l2){
return new ListNode(0);
}
$res= $ret = new ListNode(0);
$isOverTen = false;
while(1){
if($isOverTen){
$l1->val += 1;
}
if($l1->val+$l2->val >= 10){
$ret->val = $l1->val+$l2->val-10;
$isOverTen = true;
}else{
$ret->val= $l1->val+$l2->val;
$isOverTen = false;
}
$l1 = $l1->next;
$l2 = $l2->next;
if(!$l1){
$l2Flag = true;
break;
}
if(!$l2){
$l1Flag = true;
break;
}
$ret->next = new ListNode(0);
$ret = $ret->next;
}
if($l1Flag){
for(;$l1;$l1=$l1->next){
$tmp = new ListNode(0);
if($isOverTen){
if($l1->val+1 < 10){
$tmp->val = $l1->val+1;
$isOverTen=false;
}else{
$tmp->val = 0;
}
}else{
$tmp->val = $l1->val;
}
$ret->next = $tmp;
$ret = $ret->next;
}
}
if($l2Flag){
for(;$l2;$l2=$l2->next){
$tmp = new ListNode(0);
if($isOverTen){
if($l2->val+1 < 10){
$tmp->val = $l2->val+1;
$isOverTen=false;
}else{
$tmp->val = 0;
}
}else{
$tmp->val = $l2->val;
}
$ret->next = $tmp;
$ret = $ret->next;
}
}
if(!$l1 && !$l2 && $isOverTen){
$ret->next = new ListNode(1);
}
return $res;
}
}
如果下午有空,再实现下方案一的方案