我正在尝试解决一道Leetcode问题,需要在Java中实现一个链表,但是“链接”从未被创建。节点本身确实被创建了,但在内存中丢失了。我知道如何使用指针在C++中完成这个任务,但在Java中该如何实现呢?
问题:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
输出:
7
0
8
返回:
7 (just head node)
我的代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//hold root node to return later, use temp node (l3) to create list
ListNode head = new ListNode(0);
ListNode l3 = head;
boolean carryover = false;
//if lists l1, l2 still have a value, append to l3
while (l1 != null || l2 != null)
{
//always true except on first iteration
if (l3 == null)
l3 = new ListNode(0);
//if l1.val + l2.val >= 10 from last iteration, carry over 1
if (carryover)
{
l3.val += 1;
carryover = false;
}
if (l1 != null)
{
l3.val += l1.val;
l1 = l1.next;
}
if (l2 != null)
{
l3.val += l2.val;
l2 = l2.next;
}
if (l3.val > 9)
{
l3.val -= 10;
carryover = true;
}
System.out.println(l3.val);
//create next 'link' in list
l3 = l3.next;
}
return head;
}
}
Node
都有一个变量,称为next
。next
变量的类型是Node
。如果您想将新节点添加到列表中,则该方法会创建一个新的Node
并使用先前的tail
来tail.next = myNewNode;
,然后更新tail
,如tail = myNewNode;
。只需在Google上搜索“LinkedList”Java实现,就会有很多示例。 - Zabuzard