【发布时间】:2013-06-21 00:22:50
【问题描述】:
我正在阅读 Gayle Laakmann 在第 108 页的书 Crack The Coding Interview 中的链表表示的两个数字相加算法。如果您没有这本书,问题、算法和代码如下:
问题
你有两个由一个链表表示的数字,其中每个节点 包含一个数字。数字以相反的顺序存储,例如 1 的数字位于列表的首位。写一个函数 将两个数字相加,然后将 um 作为链表返回。
示例
输入:
(3->1->5),(5->9->2)输出:
8->0->8
算法
- result.data = (node1 + node2 +earlier carry) % 10
- 如果node1 + node2 > 10,则携带1到下一个加法
- 添加两个节点的尾部,沿进位传递
代码
LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) {
if (l1 == null && l2 == null) {
return null;
}
LinkedListNode result = new LinkedListNode(carry, null, null);
int value = carry;
if (l1 != null) {
value += l1.data;
}
if (l2 != null) {
value += l2.data;
}
result.data = value % 10;
LinkedListNode more = addLists(l1 == null ? null : l1.next, l2 == null ? null : l2.next, value > 10 ? 1 : 0);
result.setNext(more);
return result;
}
看到if (l1 == null && l2 == null) 后想到的显而易见的事情是,如果两个数字都为空并且仍然有进位怎么办 - 就像我们添加 999 + 999 时一样。这不会导致错误的答案吗?如果这导致正确的答案,我看不出如何。如果这导致错误的答案,我们怎样才能得到正确的答案?将前几行更改为
LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry = null) {
if (l1 == null && l2 == null) {
return carry;
}
做这个伎俩?
【问题讨论】:
-
是的,除了你必须返回一个新的 LinkedListNode。
-
哦,我差点忘了!
标签: algorithm linked-list