我正在尝试一个标准的面试问题,即以链表的形式添加两位数字并返回添加的答案。问题如下:
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
342 + 465 = 807 Make sure there are no trailing zeros in the output list So, 7 -> 0 -> 8 -> 0 is not a valid response even though
the value is still 807.
现在,我正在编写的代码采用 ListNode
数据类型形式的两个参数,这是 LinkedList 的起始节点。我不明白的是
- 如何维护列表的头节点以供稍后引用?
Java 中按值调用和按引用调用如何工作?我已经在 C++ 中处理过指针和通过引用调用,但我现在一直在 Java 中尝试一些东西,它非常不同。
class ListNode { public int val; public ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { public ListNode reverse(ListNode head) { ListNode curr = head; ListNode next = null; ListNode prev = null; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } head = prev; return head; } public ListNode addTwoNumbers(ListNode a, ListNode b) { ListNode node = null; ListNode head = null; boolean carry = false; while (a != null || b != null) { int f = 0, s = 0; if (carry) { f++; } carry = false; if (a != null) { f += a.val; a = a.next; } if (b != null) { s = b.val; b = b.next; } if (f + s > 9) { carry = true; } int curr = (f + s) % 10; node = new ListNode(curr); if (head == null) { head = node; } node = node.next; //warning that 'value of node assigned is never used' } if (carry) { node = new ListNode(1); } printList(head); return node; } }
最佳答案
node
扮演着不明确的角色。
node = new ListNode(curr);
node = node.next; // assigns null
将节点
重命名为前一个
并执行以下操作:
int curr = (f + s) % 10;
ListNode newNode = new ListNode(curr);
if (head == null) { // Or `previous == null`
head = newNode;
} else {
previous.next = newNode;
}
previous = newNode;
...
return head;
处理head
的技术是使其成为容器类LinkedList
的私有(private)字段。
与java中一样,参数传递是按值调用的:f(a)
永远不会改变变量a
:存储对象指针/值的槽。相反,将对象指针/值推送到堆栈上。 (对象值可能会更改其字段。)
因此,递归插入可能类似于 head = insert(head, ...)
。
在C中可以使用别名,不仅仅用于参数传递:
ListNode* head = NULL;
ListNode** node = &head;
shile (...) {
...
*node = newNode;
node = &(newNode->next);
}
关于java - Java中无法分配LinkedList头节点以供将来引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39789773/