Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching two elements in a Linked List

Is there a way to switch two elements in a linked list without removing and reinserting them? The code I am currently using 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.

like image 456
Jon Avatar asked Jan 13 '11 16:01

Jon


2 Answers

Use the swap method in the Collections object: http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29

like image 146
jzd Avatar answered Oct 31 '22 14:10

jzd


If you must 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 will this:

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

The second is similar to how Collections.swap is implemented. The first is slightly more efficient for a long linked list.

like image 37
finnw Avatar answered Oct 31 '22 14:10

finnw