In: Computer Science
Move all zeros in an arraylist to the end of the list using a temp(java).
if it is an array the code would look like the code below, change it to fit an arraylist
int count = 0;
int temp;
for (int i = 0; i < n; i++) {
if ((arr[i] != 0)) {
temp = arr[count];
arr[count] = arr[i];
arr[i] = temp;
count = count + 1;
}
}
}
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
ArrayList<Integer> cars = new
ArrayList<Integer>();
cars.add(0); cars.add(2); cars.add(3); cars.add(0);
cars.add(3); cars.add(0); cars.add(3);
System.out.println("Before: " + cars);
int i=0, count =0;
while(i < cars.size())
{
if(cars.get(i) == 0)
{
cars.remove(i);
i--;
count++;
}
i++;
}
while(count-- > 0)
cars.add(0);
System.out.println("After: " + cars);
}
}