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

Java Homework Help Data Structures and Algorithms 6th Edition This program invol

ID: 3597202 • Letter: J

Question

Java Homework Help

Data Structures and Algorithms 6th Edition

This program involved a LeakyStack ADT

Leaky Stack ADT

When a push is invoked on a LeakyStack at full capacity, rather than throwing an exception, accept the pushed element at the top while “leaking” the oldest element from the bottom of the stack to make room.

Write the generic interface for this LeakyStack ADT.

Give an efficient static implementation of the LeakyStack abstraction.

Provide a test of your LeakyStack that clearly shows that all of the methods work correctly.

Explanation / Answer

/* LeakyStack.java */

public class LeakyStack <Item>

{

   private Item container[];

   private int top;

   public LeakyStack (int initSize)

   {

       container = (Item[]) new Object [initSize];

       top = -1;

   }

   public Item getTop()

   {

       if (top == -1)

           return null;

       return container[top];

   }

   public boolean isEmpty()

   {

       return (top == -1);

   }

   public Item pop()

   {

       if (top == -1)

           return null;

       Item itm = container[top];

       container[top] = null; // avoid loitering

       top = (top-1+container.length)%container.length;

       return itm;

   }

   public void push(Item itm)

   {      

       top = (top + 1)%container.length;

       container[top] = itm;

   }

   // Driver program to test twoStack class

   public static void main(String args[])

   {

       LeakyStack<Integer> ts = new LeakyStack<>(5);

       ts.push(5);

       ts.push(10);

       ts.push(15);

       ts.push(11);

       ts.push(7);

       System.out.println("Popped element from" +

               " stack1 is " + ts.pop());

       ts.push(40);

       System.out.println("Popped element from" +

               " stack2 is " + ts.pop());

   }

}

/*

Sample run:

Popped element from stack1 is 7

Popped element from stack2 is 40

*/

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