Java Program to Implement Stack

Discussion DashboardCategory: JavaJava Program to Implement Stack
DHARMEDRA SAHU Staff asked 6 years ago
1 Answers
DHARMEDRA SAHU Staff answered 6 years ago

package com.dharma.datastructure;

public class MyStack {
private char[] stackArray;
private static int counter;
private int topOffStack;

public MyStack(int size){
stackArray = new char[size];
topOffStack = -1;
counter++;
}
public void push(char element){
stackArray[++topOffStack] = element;
}
public char pop(){
return stackArray[topOffStack–];
}
public char peek(){
return stackArray[topOffStack];
}
public Boolean isEmpty(){
return topOffStack<0;
}
public Boolean isFull(){
return topOffStack == stackArray.length -1;
}
public void display(){
for(int i=0;i<stackArray.length;i++){
System.out.print(stackArray[i]);
}
}
public static Integer getInstanceCounter(){
return counter;
}

}

package com.dharma.datastructure;

public class SampleMain {

/**
* @param args
*/
public static void main(String[] args) {
MyStack myStack = new MyStack(10);
myStack.push('P');
myStack.push('P');
myStack.push('P');
myStack.display();
System.out.println("myStack.isEmpty() "+myStack.isEmpty());
System.out.println("myStack.isFull() "+myStack.isFull());
System.out.println("myStack.peek() "+myStack.peek());
System.out.println("myStack.pop() "+myStack.pop());
System.out.println("myStack.isEmpty() 2 "+myStack.isEmpty());

}

}