I have to create a swap method for a java linked list. I can\'t use anything lik
ID: 3650897 • Letter: I
Question
I have to create a swap method for a java linked list. I can't use anything like Collections.swap. This is the method I have. The linked list in the main method is set up as 0,1,2,3. After calling list1.swap(1,3) the outpur should be 0,3,2,1. However I am getting 0,3,2,3. I'm sure it's some pass by value problem, but I can not solve how to do it correctly. This is my code.public void swap(int index1, int index2)
{
Node<E> ind1 = head;
Node<E> ind2 = head;
for (int i = 0; i< index1; i++)
ind1 = ind1.next;
for (int i = 0; i< index2; i++)
ind2 = ind2.next;
System.out.println("Before anything ind1 is " + ind1.element + " and ind2 is " + ind2.element);
Node<E> temp1 = ind1;
Node<E> temp2 = ind2;
System.out.println("After making temp1 and 3 equal ind1 and 2 : temp11 is " + temp1.element + " and temp2 is " + temp2.element);
ind1.element = temp2.element;
System.out.println("ind1.element = temp2.element: ind1.element is " + ind1.element + " and ind2 is " + ind2.element + " temp1.element is " + temp1.element);
ind2.element = temp1.element;
System.out.println("The end result is : ind1 is " + ind1.element + " ind2 is " + ind2.element);
}
Explanation / Answer
public void swap(int index1, int index2)
{
Node ind1 = head;
Node ind2 = head;
for (int i = 0; i< index1; i++)
ind1 = ind1.next;
for (int i = 0; i< index2; i++)
ind2 = ind2.next;
System.out.println("Before anything ind1 is " + ind1.element + " and ind2 is " + ind2.element);
Node temp1 = ind1;
Node Elem = ind1.element; // copying the element into a variable
//In your code you are copying the same element twice with the same index
System.out.println("After making temp1 and 3 equal ind1 and 2 : temp11 is " + temp1.element + " and temp2 is " + temp2.element);
ind1.element = temp2.element;//Here you are overwriting the element
System.out.println("ind1.element = temp2.element: ind1.element is " + ind1.element + " and ind2 is " + ind2.element + " temp1.element is " + temp1.element);
ind2.element = Elem;//In your code here you are copying the overwritten element
//so you are copying the same element twice
//instead of that you should copy the first value into a variable then you should copy it
System.out.println("The end result is : ind1 is " + ind1.element + " ind2 is " + ind2.element);
}