gpt4 book ai didi

Java 比较创建的链表

转载 作者:行者123 更新时间:2023-12-01 19:37:40 25 4
gpt4 key购买 nike

我将回顾创建链接列表的基础知识,并需要查明这两者在替换之前和之后是否相等。替换工作正常,因为我在主要方法中有打印语句来检查,但在替换后我无法正确比较这两个语句。问题出在我的 equals 方法中。

    public boolean replace(int index, Object newEntry) {
boolean isSuccessful = true;
Node nodeToReplace = getNode(index);
getNode(index).data = newEntry;

if(newEntry == nodeToReplace){
isSuccessful = false;
}
return isSuccessful;
} // end replace
/** Task: Determines whether two lists are equal.
* @param other object that contains the other linked list
* @return true if two lists have the same length and all
* entries are equal, or false if not */
public boolean equals(Object other) {
MyLinkedList aList = (MyLinkedList)other;
boolean isEqual = true; // result of comparison of lists
Node currentNode = firstNode;
Node aListNode = firstNode;

while ((currentNode != null)){
if (currentNode.data == aListNode.data) {
currentNode = currentNode.next;
aListNode = aListNode.next;
}
else
isEqual = false;
}
return isEqual;
} // end equals
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}

// @return an string with all entries in the list
public String toString() {
Node currentNode = firstNode;
String s = new String();
while (currentNode != null) {
s += currentNode.data + " ";
currentNode = currentNode.next;
}
return s;
}
private Node getNode(int index) {
Node currentNode = firstNode;
// traverse the list to locate the desired node
for (int counter = 0; counter < index; counter++)
currentNode = currentNode.next;
return currentNode;
} // end getNode
private class Node {
private Object data; // data portion
private Node next; // link to next node

private Node(Object dataPortion) {
data = dataPortion;
next = null;
} // end constructor
private Node(Object dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
private void setData(Object dataPortion) {
data = dataPortion;
} // end setData
private Object getData() {
return data;
} // end getData
private void setNextNode(Node nextNode) {
next = nextNode;
} // end setNextNode
private Node getNextNode() {
return next;
} // end getNextNode
} // end Node

最佳答案

它总是说它们是平等的吗?

您正在使用同一节点初始化 currentNodeaListNode:

Node currentNode = firstNode;
Node aListNode = firstNode;

您可能想要这个:

Node currentNode = firstNode;
Node aListNode = aList.firstNode;

一旦你解决了这个问题,你会发现它会永远运行。一旦您意识到两个列表不相等,您应该返回 false。然后你就可以摆脱isEqual了。现在您将 isEqual 设置为 false,但您永远不会离开循环。

关于Java 比较创建的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com