Frage

I have a linked list of names ie:(Mark, Matt, Marten, Brian, Matt) For my project I am trying to create a method where you replace one data with another and return the number of replacements.

Here were our insturctions

  • int replace( String oldData, String newData ) – replaces all occurrences of oldData with newData and returns the number of replacements made (how many times oldData was found in the list).

How do I replace strings in a linked list and return the number of replacements made?


EDIT: This is what I have tried after reviewing @LuiggiMendoza's answer:

   public int replace(String oldData, String newData )
     {
     int count = 0;
     StringNode tmp = head;
     while( tmp->next) is not null
     {
       if tmp->data equals to oldData
     {  
         tmp->data = newData
           count = count + 1;
     }
       tmp = tmp->next
     }
       return count;
     }
War es hilfreich?

Lösung 2

you have tag it as java. But few syntax are not support for java.

public int replace(String oldData, String newData )
{
     int count = 0;
     StringNode tmp = head;
     while( tmp != null)
     {
       if(tmp.data.equals(oldData)
       {  
         tmp.data = newData;
         count = count + 1;
       }
       tmp = tmp.next;
     }
     return count;

   }

Try this code in java. It should work. If the data is your own class, you have to override the equals method. Since it is string, it will work.

Andere Tipps

Iterate through the nodes of your linked list, check if the data contained in the element is equals to oldData and replace it by newData. Also, use an int counter to know how many nodes were updated.

Here's a pseudocode:

int counter = 0
Node tmp = head
while tmp->next is not null
    if tmp->data equals to oldData
        tmp->data = newData
        counter = counter + 1
    end if
    tmp = tmp->next
end while
return counter
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top