avatar
这是什么新配件?# Joke - 肚皮舞运动
c*g
1
I guess the line 3 and line 4 is not correct.
If both the linked list is NULL but the carry is 1, it should create a
new node and the value is the carry, am I right?
Thanks so much!
2.4 You have two numbers represented by a linked list, where each node
contains a single digit. The digits are stored in reverse order, such
that
the 1’s digit is at the head of the list. Write a function that adds the
two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
pg 50
SOLUTION
We can implement this recursively by adding node by node, just as we
would
digit by digit.
1. result.data = (node1 + node2 + any earlier carry) % 10
2. if node1 + node2 > 10, then carry a 1 to the next addition.
3. add the tails of the two nodes, passing along the carry.
1 LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2,
2 int carry) {
3 if (l1 == null && l2 == null) {
4 return null;
5 }
6 LinkedListNode result = new LinkedListNode(carry, null, null);
7 int value = carry;
8 if (l1 != null) {
9 value += l1.data;
10 }
11 if (l2 != null) {
12 value += l2.data;
13 }
14 result.data = value % 10;
15 LinkedListNode more = addLists(l1 == null ? null : l1.next,
16 l2 == null ? null : l2.next,
17 value > 10 ? 1 : 1);
18 result.setNext(more);
19 return result;
20 }
avatar
r*e
2
这是什么新配件?.jpg
avatar
p*e
3
line 3 and line 4 are used to test if the two input lists are empty or not

【在 c***g 的大作中提到】
: I guess the line 3 and line 4 is not correct.
: If both the linked list is NULL but the carry is 1, it should create a
: new node and the value is the carry, am I right?
: Thanks so much!
: 2.4 You have two numbers represented by a linked list, where each node
: contains a single digit. The digits are stored in reverse order, such
: that
: the 1’s digit is at the head of the list. Write a function that adds the
: two numbers and returns the sum as a linked list.
: EXAMPLE

avatar
z*c
4
外加高功率电扇啊,这么平常的电脑升级都没见过?!
avatar
s*c
5
The function already returns. How can the new node be created?
avatar
T*U
6
应该是自毁装置
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。