Jon
Jon

Reputation: 739

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.

Upvotes: 6

Views: 3549

Answers (3)

ring bearer
ring bearer

Reputation: 20813

matrix.set(i, matrix.set(j, matrix.get(i)));

Upvotes: 3

finnw
finnw

Reputation: 48659

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.

Upvotes: 4

Related Questions