Question

In: Computer Science

ArrayStack: package stacks; public class ArrayStack<E> implements Stack<E> {    public static final int CAPACITY =...

ArrayStack:

package stacks;
public class ArrayStack<E> implements Stack<E>
{
   public static final int CAPACITY = 1000; // Default stack capacity.
   private E[] data; //Generic array for stack storage.
   private int top = -1; //Index to top of stack./*** Constructors ***/
   public ArrayStack()
   {
       this(CAPACITY);
       }
   //Default constructor
   public ArrayStack(int capacity)
   {
       // Constructor that takes intparameter.
       data = (E[]) new Object[capacity];
       }
   /*** Required methods from interface ***/
   public int size()
   {
       return (top + 1);
       }
   public boolean isEmpty()
   {
       return (top == -1);
       }
   public void push(E e) throws IllegalStateException
   {
       if(size() == data.length)
       {
           throw new IllegalStateException("Stack is full!");
           }
       data[++top] = e;
       }
   public E top()
   {
       if(isEmpty())
       {
           return null;
           }
       return data[top];
       }
   public E pop()
   {
       if(isEmpty())
       {
           return null;
           }
       E answer = data[top];
       data[top] = null;
       top--;
return answer; }
}

Recall: In the array based implementation of the stack data type, the stack has a limited capacity due to the fact that the length of the underlying array cannot be changed. In this implementation, when a push operation is called on a full stack then an error is returned and the operation fails. There are certain applications where this is not useful. For example, a stack is often used to implement the \undo" feature of text editors, or the \back" button in a web browser. In these cases, it makes sense to remove the oldest element in the stack to make room for new elements. A similar data structure, called a leaky stack is designed to handle the above type of situation in a dierent manner. A leaky stack is implemented with an array as its underlying storage. When a push operation is performed on a full leaky stack, however, the oldest element in the stack is \leaked" or removed out the bottom to make room for the new element being pushed. In every other case, a leaky stack behaves the same as a normal stack. Write an implementation of the leaky stack data structure. Your class should be generic and implement the following public methods: push, pop, size, and isEmpty. Your class must also contain at least two constructors: one where the user does not specify a capacity and a default capacity of 1000 is used, and one where the user does specify a capacity.

Hint: The following is a skeleton of the class to get started (You will have to fill in the missing implementations of the abstract methods from the Stack interface):

public class LeakyStack implements Stack {

public static final int DEFAULT = 1000;

private E[] stack; private int size = 0;

private int stackTop = -1;

public LeakyStack()

{

this(DEFAULT);

}

public LeakyStack(int c);

public void push(E e);

public E pop();

public boolean isEmpty();

public int size(); }

Solutions

Expert Solution

public class LeakyStack<E>  implements Stack<E> {

        public static final int DEFAULT = 1000;

        private E[] stack; // Generic array for stack storage.
        private int stackTop = -1; // Index to top of stack./*** Constructors ***/
        private int size = 0;

        public LeakyStack() {
                this(DEFAULT);
        }

        // Default constructor
        public LeakyStack(int capacity) {
                // Constructor that takes intparameter.
                stack = (E[]) new Object[capacity];
        }

        /*** Required methods from interface ***/
        public int size() {
                return size;
        }

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

        public void push(E e) {
                if (size == stack.length) {
                        // shift one element to left.
                        for(int i=0; i<size-1; i++) {
                                stack[i] = stack[i+1];
                        }
                        stack[size-1] = e;
                } else {
                        stack[++stackTop] = e;  
                        size++;
                }
        }

        public E top() {
                if (isEmpty()) {
                        return null;
                }
                return stack[stackTop];
        }

        public E pop() {
                if (isEmpty()) {
                        return null;
                }
                E answer = stack[stackTop];
                stack[stackTop] = null;
                stackTop--;
                return answer;
        }

    public static void main(String args[]) {
        LeakyStack<Integer> s = new LeakyStack<>(5);
        
        for(int i=0; i<5; i++) {
            s.push(i);
        }
        
        System.out.println("ToP: " + s.top());

        s.push(10);
        System.out.println("ToP: " + s.top());
        s.push(20);
        System.out.println("ToP: " + s.top());
        s.push(30);
        System.out.println("ToP: " + s.top());
    }
}
**************************************************
You have not given Stack interface, so i can not run and test it.. Hence, if any issues, please ask in comments.

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

public class Square {    public static final int NUM_OF_SIDES = 4;    private float length;...
public class Square {    public static final int NUM_OF_SIDES = 4;    private float length;       public Square(float l) {        setLength(l);    }       public void setLength(float l) {        if(l >= 0) {            length = l;        }    }       public float getLength() {        return length;    }           //TODO - Add method to calculate add return area          //TODO -...
public class GroceryCart { private static final int DEFAULT_CAPACITY = 10; /* * Default constructor with...
public class GroceryCart { private static final int DEFAULT_CAPACITY = 10; /* * Default constructor with zero arguments. This constructs a grocery * cart with a default capacity of ten items. */ public GroceryCart() { } /* * Alternate constructor which takes in a maxCapacity. This maxCapacity * determines how many items can fit inside of this groceryCart. */ public GroceryCart(int maxCapacity) { } /* * Adds an item to the grocery cart. Returns true if the item was added...
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static...
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static stack of integers. Write a template that will create a static stack of any data type. Demonstrate the class with a driver program. Dynamic Stack Template In this chapter you studied DynIntStack, a class that implements a dynamic stack of integers. Write a template that will create a dynamic stack of any data type. Demonstrate the class with a driver program. Static Queue Template...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;    private int front;    private int rear;    private int[] arr;    public MyQueueImpl(int capacity){        this.capacity = capacity;        this.front = 0;        this.rear = -1;        this.arr = new int[this.capacity];    }    @Override    public boolean enQueue(int v) {                  if(this.rear == this.capacity - 1) {                //Perform shift   ...
import java.util.NoSuchElementException; public class ArrayBasedDeque<AnyType> implements deque<AnyType> {       private static int MAX_SIZE = 5;...
import java.util.NoSuchElementException; public class ArrayBasedDeque<AnyType> implements deque<AnyType> {       private static int MAX_SIZE = 5; // initial array size    //DO NOT CHANGE this, it is set to 5 to make sure your code    //will pass all the tests and works with no issue.       // add all data fields which are required    /**    * ArrayBasedDeque() constructs an empty deque.    */    public ArrayBasedDeque(){        //complete    }       /**    *...
public class P2 { public static int F(int x[], int c) { if (c < 3)...
public class P2 { public static int F(int x[], int c) { if (c < 3) return 0; return x[c - 1] + F(x, c - 1); } public static int G(int a, int b) { b = b - a; a = b + a; return a; } public static void main(String args[]) { int a = 4, b = 1; int x[] = { 3, 1, 4, 1, 5 }; String s = "Problem Number 2"; System.out.println(x[2 +...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the array to have the following property:        Suppose the first element in the original array has the value x.        In the new array, suppose that x is in position i, that is data[i] = x.        Then, data[j] <= x for all j < I and data[j] > x for all j > i.        Thus, informally, all the...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m = new int[x][y]; } public Matrix(int x, int y, int z) { m = new int[x][y]; for(int i = 0; i < x; i++) { for(int j = 0; j < y; j++) { m[i][j] = z; } } } public int rowsum(int i) throws IndexOutOfBoundsException { if (i < 0 || i > m.length-1) { throw new IndexOutOfBoundsException("Invalid Row"); } int sum =...
class ArrayStringStack { String stack[]; int top; public arrayStringStack(int size) { stack = new String[size]; top...
class ArrayStringStack { String stack[]; int top; public arrayStringStack(int size) { stack = new String[size]; top = -1; } //Assume that your answers to 3.1-3.3 will be inserted here, ex: // full() would be here //empty() would be here... //push() //pop() //displayStack() } 1. Write two boolean methods, full( ) and empty( ). 2. Write two methods, push( ) and pop( ). Note: parameters may be expected for push and/or pop. 3. Write the method displayStack( ) that prints the...
public class StringTools {    public static int count(String a, char c) {          ...
public class StringTools {    public static int count(String a, char c) {           }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT