【发布时间】:2021-07-30 13:12:59
【问题描述】:
我的链表类如下:
class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
现在在一个有签名的方法中
public ListNode getIntersectionNode(ListNode h1, ListNode h2)
我有这样的声明:
ListNode t1=h1,t2=h2;
这会产生一个编译器错误,这让我很困惑,因为在 C++ 中,我可以简单地这样做:
ListNode *t1=h1,*t2=h2;
(对于 C++ 之一,该方法将接受 ListNode *h1 and ListNode* h2)。
谁能解释为什么我不能在同一个语句中初始化多个引用?
更新最小可重现示例:
public ListNode getIntersectionNode(ListNode h1, ListNode h2) {
if (h1 == null || h2 == null)
return null;
int len1 = 0, len2 = 0;
ListNode t1 = h1, t2 = h2;
while (t1 != null) {
len1++;
t1 = t1.next;
}
while (t2 != null) {
len2++;
t2 = t2.next;
}
int diff;
diff = (len1 > len2) ? len2 - len1 : len1 - len2;
t1 = h1, t2 = h2;
if (len1 > len2)
while (diff--> 0) t1 = t1.next;
else
while (diff--> 0) t2 = t2.next;
ListNode ans = (len1 > len2) ? t1 : t2;
return ans;
}
这是完整的方法。编译器错误是:
./Solution.java:22: error: ';' expected
t1=h1,t2=h2;
【问题讨论】:
-
请显示编译器错误,给我们minimal reproducible example。您在此处显示的内容应该(/可能)没问题。
-
@AndyTurner 我已经更新了
-
错误在
diff=(len1>len2)?len2-len1:len1-len2;下一行,将t1=h1,t2=h2;替换为t1=h1; t2=h2;。
标签: java pointers pass-by-reference