In: Computer Science
public static void main(String[] args) {
//Part1: using
three stacks
iQueue<Integer> main = new
ourLinkedList<Integer>();
for (int i = 0;
i<10; i++) {
int num = -15 + (int) (Math.random() * ((15 -
(-15)) + 1));
main.add(num);
}
System.out.println("main: " +main);
iQueue<Integer> Q1 = new
ourLinkedList<Integer>();
iQueue<Integer> Q2 = new
ourLinkedList<Integer>();
while(!main.isEmpty()) {
if (main.peek() < 0)
Q1.add(main.remove());
else
Q2.add(main.remove());
}
//empty back the stacks in the
correct order
while (!Q1.isEmpty() &&
!Q2.isEmpty()) {
main.add(Q1.remove());
main.add(Q2.remove());
}
System.out.println("answer: " +main);
}
}
//This is my code using 2 constructor. I want this code to use single constructor(you dont have to change main constructor) just Q1 and Q2 and replace it with constructor Q1. this code generates alternating positive and negative numbers using the random generator. but just change the method that has following members (add, remove, isEmpty, size(), and peek() that returns front without removing it)
public static void main(String[] args) {
//Part1: using three stacks
iQueue<Integer> main = new ourLinkedList<Integer>();
for (int i = 0; i<10; i++) {
int num = -15 + (int) (Math.random() * ((15 - (-15)) + 1));
main.add(num);
}
System.out.println("main: " +main);
iQueue<Integer> Q1 = new ourLinkedList<Integer>();
iQueue<Integer> Q2 = new ourLinkedList<Integer>();
/*
* this method will only work when number of +ve numbers and number of -ve numbers are equal.
*
* and your previous code will also work on the above condition only .
*/
// Q1 will be like + - + - + -
while(!main.isEmpty()) {
if(Q1.size() %2 == 0 && main.peek() >= 0){ // if Q1 size is even and main's first element is +ve;
Q1.add(main.remove());
}
else if(Q1.size() % 2 == 1 && main.peek() < 0){ // if Q1 size is odd and main's first element is -ver;
Q1.add(main.remove());
}
else{ // if nothing add the first element to last
main.add(main.remove());
}
}
// copy Q1 into main
// main will be - + - + - +
while(!Q1.isEmpty()){
main.add(Q1.remove());
}
System.out.println("answer: " +main);
}
}