Home > Enterprise >  How do I swap two elements in a linked list without java.util.*?
How do I swap two elements in a linked list without java.util.*?

Time:10-12

Hello I am currently trying to create a method swap() that takes the position of two different elements in the linked list and swaps the the elements in the linked list. For example if I have a mercury at index 0 and we have mars at index 3, then with the swap method, it should be mars at 0 and mercury at 3. I tried making temp and swap values and within my method and setting the temp values equal to swap values so it could swap those values with each other but it seems to not work. Here's the main

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
class test{
    public static void main(String[] args){
    // You are not allowed to change the main method.
    String inputfilename = "input.txt";    
    String outputfilename= "output.txt";
    PlanetLinkedList solarSystem = constructLLFromFile(inputfilename);
    
    solarSystem.printLL();
    
   System.out.println();
    
    
    solarSystem.printLL();
    
    System.out.println();

    solarSystem.printLL();
    
    System.out.println();
    
    System.out.println("Number of nodes in the linked list: " solarSystem.countNodes());

    System.out.println();
    
    System.out.println("I will find diameter 4879 in the linked list.");
    solarSystem.search(4879);    
    System.out.println();    

    System.out.println("I will find diameter 12756 in the linked list.");
    solarSystem.search(12756);    
    System.out.println();  
    
    System.out.println("I will find Neptune in the linked list.");
    solarSystem.search("Neptune");    
    System.out.println();      
    
    System.out.println("I will find Pluto in the linked list.");
    solarSystem.search("Pluto");    
    System.out.println();          

    System.out.println("I will find Jupiter in the linked list.");
    solarSystem.search("Jupiter");    
    System.out.println();              
    
    System.out.println("I am going to remove the current head.");
    solarSystem.remove(0);
    
    System.out.println();
    
    solarSystem.printLL();
    
    System.out.println();
    
    System.out.println("I am going to insert a new record in position 4.");    
    
    Planet aNewPlanet = new Planet("Jupiter", 142984, 67);
    solarSystem.insert(aNewPlanet, 4);

    System.out.println();

    solarSystem.printLL();    
    
    System.out.println("I am going to insert a new planet in position 5.");    
    
    aNewPlanet = new Planet("Uranus", 51118, 27);
    solarSystem.insert(aNewPlanet, 5);

    System.out.println();
    
    solarSystem.printLL();
    
    System.out.println("I am going to insert a new planet in position 7.");    
    
    aNewPlanet = new Planet("Neptune", 49528, 14);
    solarSystem.insert(aNewPlanet, 7);

    System.out.println();
    
    solarSystem.printLL();
    
    
    System.out.println();   
    System.out.println("I am going to swap position 0 and 3.");    
    solarSystem.swap(0, 3);
    
    System.out.println();
    solarSystem.printLL();       
    
    System.out.println();   
    System.out.println("I am going to swap position 1 and 7.");    
    solarSystem.swap(1, 7);
    
    System.out.println();   
    System.out.println("I am going to swap position 1 and 4.");    
    solarSystem.swap(1, 4);
       
    System.out.println();
    solarSystem.printLL();      
    
    System.out.println();       
    System.out.println("I am going to write the linked list to file: " outputfilename);        
    solarSystem.writeLinkedListToFile(outputfilename);
    
  }
  
static PlanetLinkedList constructLLFromFile(String theInputFile){
    System.out.println("Constructing the linked list from " theInputFile);
    PlanetLinkedList head = new PlanetLinkedList();
    try{
      File file = new File(theInputFile);
      Scanner scan = new Scanner(file);
      int index = 0;
      while(scan.hasNext()){
        String name = scan.next();
        long diamater = Long.parseLong(scan.next());
        int moons  = Integer.parseInt(scan.next());
       
        Planet insertee = new Planet(name,diamater,moons);
        head.insert(insertee,index);
        index  ;
      }
      
      return head;

    }catch(FileNotFoundException e){
      System.out.println("file errors");
    }

    
    return null;    

  }
}

This is the linked list

import java.io.FileWriter;

class PlanetLinkedList{
  private Planet head;
  
  PlanetLinkedList(){    
  }
  
  PlanetLinkedList(Planet initial){
    head=initial;
  }
  
  PlanetLinkedList(String n, long d, int m){
    head = new Planet(n, d, m);
  }
  
 void insert(Planet insertee, int pos){
    int counter = 0;
    if(pos==0 && head == null){
      //insertee.next = head;
      head = insertee;
      return;
    }
    if(pos > countNodes() ){
      System.out.println("Error out of bounds");
      return; 
    }
    if(pos== 0){
      insertee.next = head;
      head = insertee;
      return;
   }
    Planet temp = head;
    while(temp != null){
      if(counter < pos-1){
        temp = temp.next;
        counter  ;
      }else{
         insertee.next = temp.next;
         temp.next = insertee;
         return;
      }
    }
  }  
 
 void remove(int pos){
    if(pos > countNodes() || pos < 0 ){
       System.out.println("Error out of bounds");
       return; 
    }
    if(pos == 0){
      head = head.next;
    }
    Planet temp = head.next;
    Planet prev = head;
    int counter = 0;
    while(temp != null){
      if(counter< pos-1){
        temp= temp.next;
        counter  ;
      }
      else{
        prev = temp.next;
        return;
      }
    }
  }
  
  int countNodes(){
     int count=0;
     Planet temp = head;
     while (temp != null){
      temp = temp.next;
      count  ;
     }   
    return count;
  }

  void printLL(){
    Planet temp = head;
    if(head == null){
      return;
    }
      while(temp != null ){
     System.out.println(temp.getName());
      System.out.println(temp.getDiameter());
      System.out.println(temp.getMoon());
      temp = temp.next;
   }
  }  
  //need help here!
  void swap(int pos1, int pos2){
    Planet temp = head; 
    Planet swap = temp; 
    Planet swap2 = temp;
    int counter = 0;
    if(pos1 > countNodes() || pos2 > countNodes()){
      System.out.println("Index error");
      return;
    }
    while(temp != null ){
      if(counter< pos1-1){
        temp= temp.next;
        counter  ;
      }else{
         swap = temp;
         counter = 0;
        return; 
      }
      while(temp != null){
        if(counter< pos2-1){
          temp= temp.next;
          counter  ; 
        }else{
          swap2 = temp;
          temp = swap;
          counter = 0;
          return; 
        }
      }
      while(temp != null){
        if(counter< pos1-1){
          temp= temp.next;
          counter  ;
        }else{
          swap = temp;
          temp = swap2.next;
          counter = 0;
        return; 
        }
      }
    }
  }
  
  void search (String n){
    int index = 0;
    Planet temp = head;
    boolean found = false;
    while(temp != null){
      if(n.equals(temp.getName())){
        System.out.println("The record was found at postion "   index);
        found = true;
      } 
        temp = temp.next; 
        index  ;
    }   
     if(found == false){
        System.out.println("The name "   n   " is not found in the linked list");
    }   
  }
  
  void search(long d){
    Planet temp = head;
    int index = 0;
    boolean found = false;
    while(temp != null){
      if(d == temp.getDiameter()){
        System.out.println("The record with the diameter "   d   " is found in postion "   index);
        found = true;
      }
      index  ;
      temp = temp.next;
    }
    if(found == false){
       System.out.println("The diameter "   d   " is not found in the linked list");
    } 
  }
  
  void writeLinkedListToFile(String filename){
     


  }
  
}

This is the planet class

class Planet{
  private String name;
  private long diameter;
  private int moon;
  
  Planet next;
  
  Planet(String n, long d, int m){    
    name = n;
    diameter = d;
    moon = m;
  }
  
  
  String getName(){
    return name;
  }
  
  long getDiameter(){
    return diameter;
  }
  
  int getMoon(){
    return moon;
  }
  
  public String toString(){
    return "Name: " name 
           "\nDiameter: " diameter 
           "\nMoon: " moon;
  }
}

Here is input file

Mercury
4879
0
Venus
12104
0
Earth
12756
1
Mars
6805
2
Saturn
120536
62

Thank you for the help!

CodePudding user response:

There is a lot of code in your swap() method that isn't having any effect, and I expect that this is the reason for your trouble. Let's take one small block as an example:

if(counter< pos1-1){
    temp= temp.next;
    counter  ;
}else{
     swap = temp;
     counter = 0;
    return; 
}

The first block, when if is true, makes sense. It is just moving the pointer temp along to the next node in the list. But the second block isn't doing anything. You can take out the first two lines and no behavior will change. Why? Because swap and counter are both local variables. When you call return and exit the method, those local variables disappear. So setting them has no effect. The only way to have a lasting effect is to change either head or <somenode>.next, the next pointer inside a node.

This problem is repeated a number of times in your swap() method. Here's another block:

  }else{
      swap2 = temp;
      temp = swap;
      counter = 0;
      return; 
  }

Without knowing anything else about the code except that swap2, temp and counter are local variables, I can tell you that those three lines of code before the return call will have no effect...you might as well remove them.

Rethink your logic to make sure that you are affecting the actual nodes in your linked list and you'll have better luck.

CodePudding user response:

You have insert() and remove() operations in your linked list. You should add a get(int pos) so you can read an element at position pos.

Then all you have to know is the indexes of the elements you want to swap.Then remove them from the list and insert them the other way round.

When inserting you may have to fiddle a bit with the indexes since the length of the list changed due to the removals, but that's it.

void swap(int pos1, int pos2) {
    if (pos1 == pos2)
        return; // nothing to do

    // ensure we have the first element in pos1
    if (pos1 > pos2) {
        int t = pos1;
        pos1 = pos2;
        pos2 = t;
    }

    Planet p2 = get(pos2);
    remove(pos2);

    Planet p1 = get(pos1);
    remove(pos1);

    insert(p2, pos1);
    insert(p1, pos2);
}

Note that the removal/insertion of the first position changes the list length such that the second position would change. Hence the sequence of the operations is important.

Also note that Java standard implementations of List.remove() return the removed element, which could eliminate the get() call and make the code look more elegant.

  • Related