我构建了一个获得两件事的代码。 1) 新城市的数据 2) 特定城市的名称(我们应该查找并替换为新城市)。
我的代码:
public boolean replace(City c, String x) {
CityNode temp = this._head, prev = null;
while (temp != null && temp.getCity().getCityName().equals(x)) {
prev = temp;
temp = temp.getNext();
}
if (null == temp || null == temp.getNext()) return false;
this._head = new CityNode(c);
this._head.setNext(temp.getNext().getNext());
temp.setNext(this._head);
temp.setNext(this._head);
return true;
}
根据右边输出(图片右侧)如果链表前面有3个城市...现在只有2个(在我的输出中-图片左侧)这意味着链表中的最后一个条目不会出现(显示值的顺序无关紧要)
最佳答案
如果您想替换链表中的特定节点(在您的情况下为 CityNode),您应该可以使用以下代码来完成:
public boolean replaceCity(City newCity, String cityToBeReplaced) {
CityNode temp = this._head, prev = null;
//run thru the linked list until you find the cityToBeReplaced
while(temp != null && !temp.getCity().getCityName().equals(cityToBeReplaced)) {
prev = temp;
temp = temp.getNext();
}
//cityToBeReplaced does not exist in the linked list
if(temp == null) return false;
CityNode newCityNode = new CityNode(newCity);
//First node/head is what you want to replace
if(this._head == temp) {
this._head = newCityNode;
} else {
//Last cityNode or middle cityNode is what you want to replace
prev.setNext(newCityNode);
}
newCityNode.setNext(temp.getNext());
return true;
}
关于java - 向链表添加一个值而不是特定值 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54315926/