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

Java Stacks Homework 5. Given below is part of a class declaration and construct

ID: 3883035 • Letter: J

Question

Java Stacks Homework



5. Given below is part of a class declaration and constructor for keeping two stacks within a single linear array. In this class, neither stack should overflow until all memory in the array is utilized and an entire stack should never be shifted to a different location within the array. For this class you should write the methods pushl(), push2(), popi, pop2(,clear1(, clear2), isEmptyl), isEmpty2, and isFull to manipulate the two stacks (Hint: The two stacks grow toward each other.) public class Stack private intli item; private int top1: private int top2: private int size

Explanation / Answer

import java.io.*;

class Stack {

    private int[] item;
    private int top1,top2;
    private int size;

    public Stack(int max){
          size = max;
          item = new int[size];
          top1 = -1;
          top2 = size;
    }
   public void push1(int a){
     if (!isFull1()){
         top1++;
         item[top1] = a;
     }
     else {
         System.out.println("Stack1 is full");
     }
   }
   public void push2(int a){
     if (!isFull2()){
         top2--;
         item[top2] = a;
     }
     else {
         System.out.println("Stack2 is full");
     }
   }
   public int pop1(){
       int a = item[top1];
       top1--;
       return a;
   }
    public int pop2(){
       int a = item[top2];
       top2++;
       return a;
   }
   public boolean isEmpty1(){
      if (top1==-1)
         return true;
      else
         return false;
   }
   public boolean isEmpty2(){
      if (top2==size)
         return true;
      else
         return false;
   }
   public boolean isFull1(){
      if ((top2-top1) == 1)
         return true;
      else
         return false;
   }
public boolean isFull2(){
      if ((top2-top1) == 1)
         return true;
      else
         return false;
   }
   public void clear1(){
       top1 = -1;
   }
   public void clear2(){
       top2 = size;
   }
}

public class DemoStack{
    public static void main(String[] args){

        Stack st = new Stack(5);
        st.push1(1);
        st.push2(2);
        st.push1(3);
        st.push2(4);
        System.out.println(st.pop1());
        System.out.println(st.pop2());

    }
}

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