Java dynamic stack implementation

Dynamic Stack

As we discussed in previous example that a stack throws an exception if enough space is not available to accept an entity to be pushed. To overcome this situation we can create dynamic stack whose capacity will keep increases as it reaches to max capacity.

Examples

package com.w3spoint;
 
public class Test {
private int stackSize;
private int[] stackArray;
private int top;
 
/**
 * constructor to create stack with size
 * @param size
 */
 public Test(int size) {
    this.stackSize = size;
    this.stackArray = new int[stackSize];
    this.top = -1;
}
 
/**
 * Adds new entry to the top of the stack
 * @param entry
 * @throws Exception 
 */
public void push(int entry) throws Exception {
    if(this.isStackFull()){
    	System.out.println("Stack Overflow");
    this.increaseStackCapacity();
	}
	System.out.println("Adding: "+entry);
        this.stackArray[++top] = entry;
}
 
/**
 * Removes an entry from the top of the stack.
 * @return
 * @throws Exception 
 */
public int pop() throws Exception {
    if(this.isStackEmpty()){
    	System.out.println("Stack underflow.");
	}
	int entry = this.stackArray[top--];
	System.out.println("Removed entry: "+entry);
	return entry;
}
 
/**
 * Returns top of the stack without removing it.
 * @return
 */
public int peek() {
    return stackArray[top];
}
 
/**
 * Returns true if the stack is empty
 * @return
 */
public boolean isStackEmpty() {
    return (top == -1);
}
 
/**
 * Returns true if the stack is full
 * @return
 */
public boolean isStackFull() {
    return (top == stackSize - 1);
}
 
/**
 * Increase stack capacity
 */
private void increaseStackCapacity(){	         
    int[] newStack = new int[this.stackSize*2];
    for(int i=0;i<stackSize;i++){
        newStack[i] = this.stackArray[i];
    }
    this.stackArray = newStack;
    this.stackSize = this.stackSize*2;
}
 
public static void main(String args[]){
	Test stack = new Test(3);
	try {
		for(int i=1;i<10;i++){
		    stack.push(i);
		}
		for(int i=1;i<4;i++){
			 stack.pop();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
}

Output

Adding: 1
Adding: 2
Adding: 3
Stack Overflow
Adding: 4
Adding: 5
Adding: 6
Stack Overflow
Adding: 7
Adding: 8
Adding: 9
Removed entry: 9
Removed entry: 8
Removed entry: 7
Please follow and like us:
Content Protection by DMCA.com