我是编程新手。
我知道有很多比我的方法更好更好的方法来比较两个链表。但是,因为我是新手,所以我想修复我的代码并了解我在哪里犯了错误。
我想做的是遍历两个链表
并同时比较每个节点。
比较两个链表 A 和 B => 如果它们相同则返回 1,否则返回 0。
非常感谢您的提前帮助。
int CompareLists(Node headA, Node headB) {
int i = 0;
int j = 0;
Node tmpA = headA;
Node tmpB = headB;
if(tmpB.next != null && tmpA.next == null) return 0;
while(tmpA.next != null) {
if(tmpB.next == null) return 0;
while(tmpB.next != null) {
if (i == j) {
if (tmpA.data != tmpB.data) return 0;
} else {
break;
}
tmpB = tmpB.next;
j++;
}
i++;
tmpA = tmpA.next;
}
if(tmpA.data != tmpB.data) return 0;
else return 1;
}
最佳答案
这是您的代码的清理版本。你的总体想法很好,但你确实增加了一些复杂性。
- 这两个索引是不必要的,因为您始终保持列表对齐(当 B 前进时,如果一切正常,您会中断,然后 A 也会前进)。这让我想到:
- 你不需要内部 while 和 break,只需要一个 if 来检查当前节点
- 但您确实忘记了一件事 - 当
tmpA.next
为 NULL 时,您尚未比较 A 和 B 的当前数据 - 因此您需要在循环后进行最后一次检查。<
这是一个干净的版本:
int CompareLists(Node headA, Node headB) {
Node tmpA = headA;
Node tmpB = headB;
if(tmpB.next != null && tmpA.next == null) return 0;
while(tmpA.next != null) {
if(tmpB.next == null || tmpA.data != tmpB.data) return 0;
tmpB = tmpB.next;
tmpA = tmpA.next;
}
//Added:
if(tmpB.next != null || tmpA.data != tmpB.data) return 0;
return 1;
}
当然,您不必一直处理next
。您可以只测试 tmpA/tmpB == null
等,以节省更多空间 - 我会留给您考虑。
最后的挑剔,正如@vatbub 在评论中指出的那样,尝试使用最合适的类型 - 返回 boolean 值是您在这里真正想要的。
关于java - 比较两个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49942335/