问题描述
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
大意就是两个链表相加,输出结果链表。
思路
模拟平时列竖式做加法运算的过程即可。有几个点需要考虑:
- 进位的保存。因为最大只能是 9 + 9 = 18,所以进位只可能为 0 或 1
- 2位整数取最低位。直接除以10即可。
- 最高位的进位。 如 L1 = 9, L2 = 1, 这时结果表L3 = 10, 比L1, L2多一个结点
Go实现
用时26ms, 击败了85%(用golang的)人
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// 进位值, 只可能为0或1
promotion := 0
// 结果表的头结点
var head *ListNode
// 保存结果表的尾结点
var rear *ListNode
for nil != l1 || nil != l2 {
sum := 0
if nil != l1 {
sum += l1.Val
l1 = l1.Next
}
if nil != l2 {
sum += l2.Val
l2 = l2.Next
}
sum += promotion
promotion = 0
if sum >= 10 {
promotion = 1
sum = sum % 10
}
node := &ListNode{
sum,
nil,
}
if nil == head {
head = node
rear = node
} else {
rear.Next = node
rear = node
}
}
if promotion > 0 {
rear.Next = &ListNode{
promotion,
nil,
}
}
return head
}