我正在介绍创建链接列表的基础知识,并需要找出这两个列表在替换前后是否相等。当我在主要方法中使用打印语句时,替换的工作正常,但是我以某种方式无法正确比较替换之后的这两个。问题在于我的平等方法。
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
总是说它们相等吗?
您使用相同节点初始化currentNode
和aListNode
:
Node currentNode = firstNode;
Node aListNode = firstNode;
您可能想要这个:
Node currentNode = firstNode;
Node aListNode = aList.firstNode;
解决此问题后,您会发现它永远运行。一旦意识到这两个列表不相等,就应该使用return false
。然后,您可以摆脱isEqual
。现在,您将isEqual
设置为false,但您永远不会离开循环。
在您的 equals
功能中,您在同一地点同时启动currentNode
和aListNode
。
我相信您想将currentNode
初始化为旧列表,然后将aListNode
初始化为新列表,或者是对反面列表以比较它们,否则您将始终从函数中获得真正的返回