原创文章转载请注明出处
Add Two Numbers
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
其实就是列加法竖式,C的速度无人能敌。我所熟悉的语言中,JavaScript依然垫底,但是同样是编译型的Swift会差Go那么多实在是大跌眼镜,指针和结构体初始化的操作效率还是高。
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 currentL1 = l1
var currentL2 = l2
let rootNode = ListNode(0)
var currentNode : ListNode? = rootNode
var overflow : Int = 0
while (currentL1 != nil || currentL2 != nil || overflow != 0) {
// compute current node
let sum = overflow + (currentL1?.val ?? 0) + (currentL2?.val ?? 0)
if sum >= 10 {
currentNode?.next = ListNode( sum - 10 )
overflow = 1
} else {
currentNode?.next = ListNode( sum )
overflow = 0
}
// prepare data for next step
currentNode = currentNode?.next
currentL1 = currentL1?.next
currentL2 = currentL2?.next
}
return rootNode.next
}
}
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
overflow := 0
head := new(ListNode)
cur := head
for l1 != nil || l2 != nil || overflow != 0 {
n1, n2 := 0, 0
if l1 != nil {
n1, l1 = l1.Val, l1.Next
}
if l2 != nil {
n2, l2 = l2.Val, l2.Next
}
num := n1 + n2 + overflow
if num >= 10 {
overflow = 1
cur.Next = &ListNode{Val:num-10, Next:nil}
} else {
overflow = 0
cur.Next = &ListNode{Val:num, Next:nil}
}
cur = cur.Next
}
return head.Next
}
我是咕咕鸡,一个还在不停学习的全栈工程师。
热爱生活,喜欢跑步,家庭是我不断向前进步的动力。