题目: 两个链表表示的证书,每个结点包含一个数位,数位是反向存放,即个位排在链表首部.对两个整数求和,并用链表形式返回结果.
解法一
两个链表同时遍历,相加之后进位向前进一位,�余数作为当前的数值存储.
核心代码:
<pre><code>` func addListNode(node1:ListNode,node2:ListNode) -> ListNode {
var first:ListNode? = node1
var second:ListNode? = node2
var result:ListNode?
var carry:Int = 0
while first != nil || second != nil {
var num1:Int = 0
if (first?.value) != nil {
num1 = Int((first?.value)!)!
}
var num2:Int = 0
if second?.value != nil {
num2 = Int((second?.value)!)!
}
let value:Int = num1 + num2 + carry
let mod:Int = value % 10
carry = value / 10
let node:ListNode = ListNode(value: "\(mod)")
if result == nil {
result = node
} else {
var nextNode:ListNode? = result
while nextNode?.next != nil {
nextNode = nextNode?.next
}
nextNode?.next = node
}
first = first?.next
second = second?.next
}
return result!
}`</code></pre>
解法二
当然也可以通过递归的方式,返回最后的节点.
核心代码:
<pre><code>` func addListNode1(node1:ListNode?,node2:ListNode?,carry:Int) -> ListNode? {
if node1 == nil && node2 == nil && carry == 0 {
return nil
}
var value:Int = carry
if node1?.value != nil {
value += Int((node1?.value)!)!
}
if node2?.value != nil {
value += Int((node2?.value)!)!
}
let mod:Int = value % 10
let nextCarry:Int = value / 10
let result:ListNode = ListNode(value: "\(mod)")
let nextNode:ListNode? = addListNode1(node1: node1?.next, node2: node2?.next, carry: nextCarry)
result.next = nextNode
return result
}`</code></pre>
测试代码:
<pre><code>`listNodeManger.appendToTail(value: "(0)")
listNodeManger.appendToTail(value: "(5)")
listNodeManger.appendToTail(value: "(2)")
listNodeManger.appendToTail(value: "(7)")
var addHeadNode1:ListNode = listNodeManger.headNode!
listNodeManger.headNode = nil
listNodeManger.appendToTail(value: "(7)")
listNodeManger.appendToTail(value: "(8)")
listNodeManger.appendToTail(value: "(9)")
var addHeadNode2:ListNode = listNodeManger.headNode!
var addResultNode:ListNode = listNodeManger.addListNode(node1: addHeadNode1, node2: addHeadNode2)
print("FlyElephant---链表原始数据")
listNodeManger.printListNode(headNode: addHeadNode1)
listNodeManger.printListNode(headNode: addHeadNode2)
print("FlyElephant---相加之后结果")
listNodeManger.printListNode(headNode: addResultNode)
var addResultNode2:ListNode? = listNodeManger.addListNode1(node1: addHeadNode1, node2: addHeadNode2, carry: 0)
print("FlyElephant---相加之后结果2")
listNodeManger.printListNode(headNode: addResultNode2!)`</code></pre>