Toggle two items in a linked list

Is there a way to switch two items in a linked list without deleting and reinserting them? The code I use is:

void exchange(int i, int j) { int[] temp = matrix.get(i); matrix.remove(i); matrix.add(i, matrix.get(j - 1)); matrix.remove(j); matrix.add(j, temp); } 

where matrix is my linked list.

+6
java linked-list
source share
3 answers

If you have to implement it yourself, this will work:

 void exchange(int i, int j) { ListIterator<int[]> it1 = matrix.listIterator(i), it2 = matrix.listIterator(j); int[] temp = it1.next(); it1.set(it2.next()); it2.set(temp); } 

as it will be:

 void exchange(int i, int j) { matrix.set(i, matrix.set(j, matrix.get(i))); } 

The second is similar to the implementation of Collections.swap . The first is a bit more efficient for a long linked list.

+4
source share
+5
source share
 matrix.set(i, matrix.set(j, matrix.get(i))); 
+3
source share

All Articles