Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method splitStack that takes a stack of integers as a parameter and spli

ID: 644255 • Letter: W

Question

Write a method splitStack that takes a stack of integers as a parameter and splits it into negatives and non-negatives. The numbers in the stack should be rearranged so that all the negatives appear on the bottom of the stack and all the non-negatives appear on the top. In other words, if after this method is called you were to pop numbers off the stack, you would first get all the nonnegative numbers and then get all the negative numbers. It does not matter what order the numbers appear in as long as all the negatives appear lower in the stack than all the non-negatives. You may use a single queue as auxiliary storage.

Explanation / Answer

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class StackOps{
  
   public static void modify(Stack<Integer> s){
       Queue<Integer> t = new LinkedList<Integer>();
       int count = 0;
       while(s.size() != 0){
           Integer temp = s.pop();
           t.add(temp);
           if(temp.intValue() >= 0){
               count++;
           }
       }
       while(t.size() != 0){
           Integer temp = t.remove();
           if(temp.intValue() < 0){
               if(s.size() >= count){
                   s.push(temp);
               }
               else{
                   t.add(temp);
               }
           }
           else{
               s.push(temp);
           }
       }
   }
  
   public static void main(String args[]){
       Stack<Integer> s = new Stack<Integer>();
       s.push(new Integer(25));
       s.push(new Integer(-23));
       s.push(new Integer(17));
       s.push(new Integer(41));
       s.push(new Integer(-35));
       s.push(new Integer(-21));
       s.push(new Integer(27));
       System.out.println(s);
       modify(s);
       System.out.println(s);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote