给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解题思路:
Java实现
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode resultHeader = new ListNode(0); ListNode next1 = l1, next2 = l2, sumNext = resultHeader; int up, sum; boolean doSum = true; while (doSum) { if (next1 == null && next2 != null) { sum = sumNext.val + next2.val; next2 = next2.next; } else if (next1 != null && next2 == null) { sum = sumNext.val + next1.val; next1 = next1.next; } else { sum = next1.val + next2.val + sumNext.val; next1 = next1.next; next2 = next2.next; } up = sum / 10; sumNext.val = up > 0 ? sum - 10 : sum; if ((doSum = next1 != null || next2 != null) || up > 0) { sumNext.next = new ListNode(up); sumNext = sumNext.next; } } return resultHeader; }
Golang实现
这道题Go的执行速度虽然超过了97%了Go的提交,但是居然比java慢!
提交结果
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { header := ListNode{0, nil} next1, next2, sumNext := l1, l2, &header up, sum := 0, 0 doSum := true for doSum { if next1 == nil && next2 != nil { sum = sumNext.Val + next2.Val next2 = next2.Next } else if next2 == nil && next1 != nil { sum = sumNext.Val + next1.Val next1 = next1.Next } else { sum = sumNext.Val + next1.Val + next2.Val next2 = next2.Next next1 = next1.Next } up = sum / 10 if up > 0 { sumNext.Val = sum - 10 } else { sumNext.Val = sum } doSum = next1 != nil || next2 != nil if doSum || up > 0 { sumNext.Next = &ListNode{up, nil} sumNext = sumNext.Next } } return &header }
来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。