Simple Array Stack Implementation using JAVA Example 1661 views. SimpleArrayBasedImplementation.java //size, isEmpty, push, top, pop, toString
class StackImpl {
private int capacity;
//default capacity
private final static int DEFAULT_CAPACITY = 10;
//top pointer
private int top = -1;
//stack holder
private int[] stackArray;
//Allocate memory with default capacity
public StackImpl() {
//by default array initialize
this(StackImpl.DEFAULT_CAPACITY);
}
//Allocate memory with custom capacity
public StackImpl(int capacity) {
this.capacity = capacity;
stackArray = new int[this.capacity];
}
//To get size of the stack
public int size() {
return top + 1;
}
//To check stack isEmpty
public boolean isEmpty(){
return top == -1;
}
//Push ADT
public void push(int data) throws Exception {
//Exception handling - if stack is full
if (size() == capacity) {
throw new Exception("Stack is full!");
}
//Otherwise add data to the stack.
stackArray[++top] = data;
}
//Reading Top value
public int top() throws Exception {
//Exception handling - if stack is empty
if (isEmpty()) {
throw new Exception("Stack is empty!");
}
//Otherwise return top value.
return stackArray[top];
}
//Pop ADT
public int pop() throws Exception {
//Exception handling - if stack is empty
if (isEmpty()) {
throw new Exception("Stack is empty!");
}
//Otherwise pop the top element
int data = stackArray[top];
stackArray[top--] = 0;
return data;
}
//toString stackArray
public String toString() {
String arrayString = "[";
for (int index = 0; index <= top; index++) {
if (index == 0) {
//adding data if index is 0
arrayString += stackArray[index];
}
else {
//adding data with comma if index is not 0.
arrayString += "," + stackArray[index];
}
}
arrayString += "]";
return arrayString;
}
}
/*
Simple array stack implemantion
in JAVA with Example program
*/
public class SimpleArrayBasedImplementation {
public static void main(String[] args) {
//Using custom stack
StackImpl stack = new StackImpl(5);
try {
//check stack is empty
System.out.println("isEmpty: "+stack.isEmpty());
//adding data to the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
//will throw stack is full exception
//stack.push(60);
//print stack
System.out.println("Stack: "+stack);
//top element
System.out.println("Top: "+stack.top());
System.out.println("Stack: "+stack);
//pop element
System.out.println("Pop data: "+stack.pop());
System.out.println("Stack: "+stack);
//read size of the stack
System.out.println("Size is "+stack.size());
//check stack is empty
System.out.println("isEmpty: "+stack.isEmpty());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output isEmpty: true
Stack: [10,20,30,40,50]
Top: 50
Stack: [10,20,30,40,50]
Pop data: 50
Stack: [10,20,30,40]
Size is 4
isEmpty: false
Related Examples
|
|