//Stack DataStructure Using Array
package stack;
public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
if(isFull()) {
System.out.println("Stack is Full");
} else {
top++;
stackArray[top] = j;
}
}
public long pop() {
if(top < 0) {
System.out.println("Stack Underflow");
return 0;
}else{
long item = stackArray[top];
top--;
return item;
}
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize-1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.println("Values are: "+value);
}
System.out.println("Is Empty Now: "+theStack.isEmpty()); //true
}
}
//Output
Values are: 50
Values are: 40
Values are: 30
Values are: 20
Values are: 10
Is Empty Now: true
Wednesday, April 26, 2017
Stack Data Structure Using Array in Java
Subscribe to:
Posts (Atom)