java - 向链表添加一个值而不是特定值 - JAVA

标签 java linked-list

我构建了一个获得两件事的代码。 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个(在我的输出中-图片左侧)这意味着链表中的最后一个条目不会出现(显示值的顺序无关紧要)

enter image description here

最佳答案

如果您想替换链表中的特定节点(在您的情况下为 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/

相关文章:

java - 如何删除我在链接列表中选择的两个元素之间的所有元素

c - 添加到C中的链接列表

c - 通过构建尾部优化链表中的一个特例

java - 克隆单向链表

c - 双链表C编程中反向查看/搜索功能的问题

java - ColdFusion 中 java.util.ArrayList 的用法

java - 从 .jsp 格式的 xml 中提取内容

java - 处理月份和日期时出现 ParseException

java - 在与当前类同名的类上使用 Spring @Autowired

java - C++和Java中的异常处理之间的区别?