Write moveNegativesToEnd(), which takes a stack of integers and re-orders its va
ID: 3826583 • Letter: W
Question
Write moveNegativesToEnd(), which takes a stack of integers and re-orders its values so that all the negatives appear on the bottom of the stack and all of the non-negatives appear on the top. Here is a smaple tester and its associated output: public static void main(string[] args) {Stack s = new stack (); s. push (-5); s. push (3); s. push (-2); s.push(2); moveNegativeToEnd(s); while(!s. isEmpty()) out.print(s.pop() + ""); Output It does what order the non-negatives appear in. Same for the negatives. It only matter that the non-negatives a ear first. When accessing a stack, your method can only use push(), pop(), peek (), size (), and isEmpty (). Your method can use other data structures if needed. Your function must be less than 20 lines long. Here is the first line of your function: private static void moveNegativesToEnd (Stacks s) {Explanation / Answer
public static void main(String[] argv){
Stack<Integer> s = new Stack<>();
s.push(-5); s.push(3); s.push(-2); s.push(2);
moveNegativeToEnd(s);
while(!s.isEmpty()){
System.out.print(s.pop()+" ");
}
}
public static void moveNegativeToEnd(Stack<Integer> s){
Stack<Integer> positive =new Stack<>();
Stack<Integer> negative =new Stack<>();
while(!s.isEmpty()){
int num = s.pop();
if(num<0)
negative.push(num);
else
positive.push(num);
}
while(!negative.isEmpty()){
s.push(negative.pop());
}
while(!positive.isEmpty()){
s.push(positive.pop());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.