题目:两数相加

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

解题思路

1、将两个链表看成是相同长度的进行遍历,如果一个链表较短则在前面补 00,比如 987 + 23 = 987 + 023 = 1010
2、每一位计算的同时需要考虑上一位的进位问题,而当前位计算结束后同样需要更新进位值
3、如果两个链表全部遍历完毕后,进位值为 11,则在新链表最前方添加节点 11

小技巧:对于链表问题,返回结果为头结点时,通常需要先初始化一个预先指针 pre,该指针的下一个节点指向真正的头结点head。使用预先指针的目的在于链表初始化时无可用节点值,而且链表构造过程需要指针移动,进而会导致头指针丢失,无法返回结果。

代码

/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {

var list1 = l1
var list2 = l2

val pre = ListNode(0)
var cur = pre
// 存储每次计算的时候的进位值
var carry = 0

while(list1!=null || list2!=null){
// 如果当前位置无节点,就用0来相加
val a = if(list1==null) 0 else list1.`val`
val b = if(list2==null) 0 else list2.`val`

val sum = a + b + carry

val digit = sum % 10
carry = sum/10

// 数字0-9
cur.next = ListNode(digit)

// 链表指针后移1位
cur = cur.next!!
if(list1!=null) list1 = list1.next
if(list2!=null) list2 = list2.next

}

// 最后一位如果有进位,需要再移1位
if(carry==1) cur.next = ListNode(1)

return pre.next

}
}

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.

参考资料

​https://leetcode-cn.com/problems/add-two-numbers/​

​https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-lian-biao-cao-zuo-by-chenguang/​


Kotlin开发者社区


LeetCode 2. 两数相加:链表操作_git


专注分享 Java、 Kotlin、Spring/Spring Boot、MySQL、redis、neo4j、NoSQL、Android、JavaScript、React、Node、函数式编程、编程思想、"高可用,高性能,高实时"大型分布式系统架构设计主题。