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

Hi I want this question to solve in java. 1. The array implementation in this ch

ID: 3838038 • Letter: H

Question

Hi

I want this question to solve in java.

1. The array implementation in this chapter keeps the top variable pointing to the next array position above the actual top of the stack. Rewrite the array implementation such that stack[top] is the actual top of the stack.

2. There is a data structure called a dropout stack that behaves like a stack in every respect, except that if the stack size is n, when the n + 1 element is pushed, the first element is lost.  Implement a dropout stack using an array.

thanks

Explanation / Answer

1.

// ArrayStack.java

public class ArrayStack {
private int top;
private final int size;
private int[] stack ;

public ArrayStack(int arraySize) throws Exception{
   if (arraySize <= 0){
       throw new Exception("Size should be a positive value");
   }
size=arraySize;
stack= new int[size];
top=-1;
}

public void push(int value) throws Exception{
if(top==size-1){
throw new Exception("Stack is full, can't push a value");
}
else{
top=top+1;
stack[top]=value;
}
}

public int pop() throws Exception{
if(!isEmpty()) {
   return stack[top--];
}
else{
throw new Exception("Can't pop...stack is empty");
}
}

public boolean isEmpty(){
return top==-1;
}

@Override
public String toString(){
   StringBuilder sb = new StringBuilder();
   if (!isEmpty())
   {
   for(int i=top;i>=0;i--){
   sb.append(stack[i]+ " ");
   }
   }
return sb.toString();
}
}

// ArrayStackTest.java


public class ArrayStackTest {
   public static void main(String[] args) {
ArrayStack newStack = null;
       try {
           newStack = new ArrayStack(5);
       } catch (Exception e) {
           System.out.println(e.getMessage());
       }
       for (int i = 0; i < 5; i++)
       {
           try
           {
               newStack.push(10*i);
   }
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
       }
  
System.out.println(newStack);
  
for (int i = 0; i < 5; i++)
       {
   try
   {
       System.out.println("Popped: " + newStack.pop());
   }
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
       }
System.out.println(newStack);
}
}

// Sample run

40 30 20 10 0
Popped: 40
Popped: 30
Popped: 20
Popped: 10
Popped: 0

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