简体   繁体   中英

swap nodes from a linked list java

I am trying to swap two nodes from given positions from a linked list, I currently have done this but nothing is being swapped and I also have to make sure to print an error if they pick a position that is not on the linked list for example there are 5 nodes so if a position is 6 it should print an error where can I put that message. The method can't be changed from the way it is

void swapping(int a, int b){
POI curr1;
POI temp = head;
POI temp1;
int i = 1;
POI temp2;
POI curr2;
while(i < a - 1){
  temp= temp.next;
  i++;
}
temp1 = temp;
curr1 = temp1.next;

while(i < b - 1){
  temp= temp.next;
  i++;
}
temp2 = temp;
curr2 = temp2.next;

temp = curr1.next;
temp2.next = curr1;
curr1.next = curr2.next;

you should read about "pass by reference" vs "pass by value" in java, primitives (in your case int a, int b ) are passed by value - meaning java makes a copy of those values, and once method exits - those values no longer exists.

so technically you can't void swap (int a, int b) you'll need a wrapper for that. (indeed there are boxed primitives eg - Integer , but they also won't work in this case because they are immutable)

you should do something like:

 class IntWrapper {
   int value
 }
 
 void swap(IntWrapper a, IntWrapper b) {
   int temp = a.value;
   a.value = b.value;
   b.value = temp.value;
 }

because IntWrapper is an Object it is passed by reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM