Issue
I'm trying to figure out how to take in an integer and rearrange them so that every alternating character is saved (So the [1, 2, 3, 4, 5, 6] would return [1, 4, 2, 5, 3, 6]). I think a queue would be the best to use for this problem so here's what I have so far. It returns [3, 1, 4, 5, 2, 6], but I'm not sure how I can get it to return the alternating form above :
import java.util.*;
public class everyOtherInteger {
public static void main(String[] args) {
Queue <Integer> sort = new LinkedList<Integer>();
String s = "123456";
for (int i = 0; i < s.length(); i++) {
sort.add(Integer.parseInt(s.charAt(i) + ""));
if (i%2 == 0) {
int a = sort.remove();
sort.add(a);
}
else {
}
}
System.out.println(sort);
}
}
Solution
Just build the list differently. No queue required.
You can add half the numbers at the start, the add the rest in-between each.
List<Integer> nums = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int limit = sc.nextInt(); // 6
int value = 1;
for (int i = 0; i < limit / 2; i++) {
nums.add(value++);
}
for (int i = 1; i < limit; i+=2) {
nums.add(i, value++);
}
System.out.println(nums); // [1, 4, 2, 5, 3, 6]
Answered By - OneCricketeer