将由链表表示的两个数字相加
这里我们将看到如何将存储在单独链表中的两个数字相加。在链表中,存储了数字的每一位数字。如果数字是 512,那么它将像下面一样存储 -
512 = (5)-->(1)-->(2)-->NULL登录后复制
算法
addListNumbers(l1, l2)
Begin Adjust the l1 and l2 lengths by adding leading 0s with the smaller one carry := 0 res := an empty list for each node n from l1, scan from last to first, do item := (l1.item + l2.item + carry) mod 10 insert item at the beginning of res carry := (l1.item + l2.item + carry) / 10 done if carry is not 0, then add carry at the beginning of res end if return res End登录后复制