Array Implementation of Stack - Java
public class ArrayImplementation {
private int maxSize;
private int stack[];
private int top;
public ArrayImplementation(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
this.top = -1;
}
public void push(int data){
if(!isFull())
stack[++top] = data;
}
public int pop(){
if(!isEmpty())
return stack[top--];
else
return -1;
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize-1);
}
public static void main(String[] args) {
ArrayImplementation theStack = new ArrayImplementation(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.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
private int maxSize;
private int stack[];
private int top;
public ArrayImplementation(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
this.top = -1;
}
public void push(int data){
if(!isFull())
stack[++top] = data;
}
public int pop(){
if(!isEmpty())
return stack[top--];
else
return -1;
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize-1);
}
public static void main(String[] args) {
ArrayImplementation theStack = new ArrayImplementation(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.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
Output:
50 40 30 20 10
Comments
Post a Comment