Beto
Beto

Reputation: 806

How to reverse an ArrayList without the reverse method?

Hello I am trying to reverse an ArrayList without the reverse method. I just wanted to make it work without the method. I can't seem to get it right. This is what i have so far:

for (int x = nums.size()-1; x>=0; x--)
    {

        for(int z =0; z<nums.size();z++)
        {
            nums.set(z, x);

        }
    }

This is my output: run: 0 1 2 3

1 1 1 1 BUILD SUCCESSFUL (total time: 0 seconds)

Upvotes: 0

Views: 4540

Answers (2)

SimonT
SimonT

Reputation: 2369

You can swap in pairs at a time, coming in from both ends toward the center:

for (int i = 0; i < nums.size()/2; i++) {
    Integer left = nums.get(i);
    Integer right = nums.get(nums.size()-1-i);
    nums.set(i, right);
    nums.set(nums.size()-1-i, left);
}

By using Integer instead of int for left and right, Java doesn't have to keep converting between int and Integer values (the first being a primitive, the second being an actual object). This improves performance.

Upvotes: 0

Thomas W
Thomas W

Reputation: 14154

You can ascend from the bottom & simultaneously descend from the top (size() - 1) swapping elements, and stop when you meet in the middle.

int i = 0;
int j = nums.size()-1;
while (i < j) {
    int temp = nums.get(i);
    nums.set( i, nums.get(j));
    nums.set( j, temp);
    i++; j--;
}

Upvotes: 1

Related Questions