原創(chuàng)文章轉(zhuǎn)載請(qǐng)注明出處
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
其實(shí)就是列加法豎式,C的速度無(wú)人能敵。我所熟悉的語(yǔ)言中行施,JavaScript依然墊底逞带,但是同樣是編譯型的Swift會(huì)差Go那么多實(shí)在是大跌眼鏡,指針和結(jié)構(gòu)體初始化的操作效率還是高怠惶。
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
}
我是咕咕雞,一個(gè)還在不停學(xué)習(xí)的全棧工程師。
熱愛(ài)生活奸例,喜歡跑步,家庭是我不斷向前進(jìn)步的動(dòng)力向楼。