boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 150上这个是不是不对? (转载)
相关主题
careerup 2.4的答案是不是不对呀?!
问一个题目
A onsite被拒,面经,求分析失败原因
面试的时候 binary tree的delete也要15分钟之内写完么?
问个二叉树删除结点的问题
一道题:2个BST,按大小顺序打印两棵树的所有节点
LCA复杂度是多少
发现一个很恶心的基础问题
MS onsite面经
help: leetcode "Recover Binary Search Tree" -- 附代码
相关话题的讨论汇总
话题: null话题: carry话题: value话题: node
进入JobHunting版参与讨论
1 (共1页)
c***g
发帖数: 472
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 }
p*****e
发帖数: 53
2
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

s******c
发帖数: 99
3
The function already returns. How can the new node be created?
1 (共1页)
进入JobHunting版参与讨论
相关主题
help: leetcode "Recover Binary Search Tree" -- 附代码
自己写了个graph的class但是不work 求指点
Recover Binary Search Tree:以前的解法通不过了
How can one determine whether a singly linked list has a cycle?
一个Linkedlist面试题的教训
linked list排序的算法除了bubble
CISCO 面经,有点坑爹。顺便请教一题。
Flatten Binary Tree to Linked List的recursive解法
问最小窗口覆盖的面试题
Least Common Ancester算法最优解
相关话题的讨论汇总
话题: null话题: carry话题: value话题: node