题目:题目: 两个链表表示的证书,每个结点包含一个数位,数位是正向存放,即个位排在链表尾部.对两个整数求和,并用链表形式返回结果.
同上一篇文章类似,可以通过递归来实现,不过思考两个问题,递归之后不仅需要返回节点,还需要返回进位.链表长短不一致,数位相加不要出错.
<pre><code>class ListNodeSum { var node:ListNode? var carry:Int = 0 }
</code></pre>
核心代码:
<pre><code>` func listNodeCount(listNode:ListNode) -> Int {
var node:ListNode? = listNode
var count:Int = 0
while node != nil {
count += 1
node = node?.next
}
return count
}
func paddingListNode(node:ListNode,padding:Int) -> ListNode {
var head:ListNode = node
for _ in 0..<padding {
let listNode:ListNode = ListNode(value: "\(0)")
listNode.next = head
head = listNode
}
return head
}
func insertBefore(node:ListNode?,value:Int) -> ListNode {
let listNode:ListNode = ListNode(value: "\(value)")
listNode.next = node
return listNode
}
func addListNode3(node1:ListNode,node2:ListNode) -> ListNode? {
let count1:Int = listNodeCount(listNode: node1)
let count2:Int = listNodeCount(listNode: node2)
var first:ListNode = node1
var second:ListNode = node2
if count1 > count2 {
second = paddingListNode(node: second, padding: count1 - count2)
} else {
first = paddingListNode(node: first, padding: count2 - count1)
}
let sumNode:ListNodeSum? = addListHelper(node1: first, node2: second)
if sumNode?.node != nil {
if sumNode?.carry == 0 {
return sumNode?.node
} else {
let result:ListNode = insertBefore(node: sumNode?.node, value: (sumNode?.carry)!)
return result
}
}
return nil
}
func addListHelper(node1:ListNode?,node2:ListNode?) -> ListNodeSum? {
if node1 == nil && node2 == nil {
return ListNodeSum()
}
let sumNode:ListNodeSum? = addListHelper(node1: node1?.next, node2: node2?.next)
var value:Int = 0
if node1?.value != nil {
value += Int((node1?.value)!)!
}
if node2?.value != nil {
value += Int((node2?.value)!)!
}
if sumNode != nil {
value += (sumNode?.carry)!
}
let fullNode:ListNode? = insertBefore(node: sumNode?.node, value: value % 10)
sumNode?.carry = value / 10
sumNode?.node = fullNode
return sumNode
}`</code></pre>
测试代码:
<pre><code>`listNodeManger.headNode = nil
listNodeManger.appendToTail(value: "(9)")
listNodeManger.appendToTail(value: "(5)")
listNodeManger.appendToTail(value: "(8)")
var sequenceHeadNode1:ListNode! = listNodeManger.headNode
listNodeManger.headNode = nil
listNodeManger.appendToTail(value: "(8)")
listNodeManger.appendToTail(value: "(7)")
var sequenceHeadNode2:ListNode! = listNodeManger.headNode
var sequenceHeadNode3:ListNode? = listNodeManger.addListNode3(node1: sequenceHeadNode1, node2: sequenceHeadNode2)
print("FlyElephant---正向相加结果")
listNodeManger.printListNode(headNode: sequenceHeadNode3!)`</code></pre>