0

I built a code that getting two things. 1) Data on a new city 2) The name of a particular city (which we are supposed to look for and replace with the new city).

My code:

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;
 }

According to the right OUTPUT that comes out (the right side of the picture) if there were 3 cities in front of the linked list ... now there are only 2 (in my output - the left side of the picture) which means that the last entry in the linked list does not appear (The order of values ​​displayed does not matter)

enter image description here

AnnaLA
  • 155
  • 1
  • 11

1 Answers1

1

If you want to replace a specific node in a linked list (CityNode in your case), you should be able to do it using below code:

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;
}
ankitkpd
  • 663
  • 5
  • 19