[Leetcode]2. Add Two Numbers
2017-05-16 本文已影响50人
邓国辉
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
大意为:给定两个链表,链表中的值为非负整数,将两个链表中的值相加
思路:
从list1, list2头节点开始,对应位置相加并建立新节点。用一个变量carry记录进位。注意几种特殊情况:
-
一个链表为空
l1: NULL
l2: 1->2
sum: 1->2 -
l1, l2长度不同,且结果有可能长度超过l1, l2中的最大长度
l1: 2->2
l2: 9->9->9
sum: 1->2->0->1
// in swift
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var carry = 0
var list1 = l1, list2 = l2
let dummy = ListNode(0)
var pre = dummy
while list1 != nil || list2 != nil {
let val1: Int = list1?.val ?? 0
let val2: Int = list2?.val ?? 0
let val = val1 + val2 + carry
pre.next = ListNode(val % 10)
pre = pre.next!
carry = val >= 10 ? 1: 0
list1 = list1?.next
list2 = list2?.next
}
if carry != 0 {
pre.next = ListNode(1)
}
return dummy.next
}
}