Skip to content

2.4 Stack using Array

Farrukh Ahmad edited this page Dec 15, 2015 · 1 revision

Stack stands with a concept of FIFO

 public class SimpleStack {

public static void main(String[] args) {
	MyStack stack = new MyStack(10);
	stack.push(10);
	stack.push(20);
	
	System.out.println(stack.pop());
	System.out.println(stack.pop());
	
	System.out.println(stack.pop());
}
}


class MyStack
{
int size = 0;
int top=-1;
Object stack[] = null;

public MyStack(int size) {
	stack= new Object[size];
}


public void push(Object item){
	if(size == stack.length){
		System.out.println("Overflow!!!");
		return;
	}
	stack[++top] = item;
	size++;
}

public Object pop(){
	if(size==0){
		System.out.print("Underflow!!!");
		return null;
	}
	Object item = stack[top];
	stack[top--] = null;
	size--;
	return item;
}
}

Clone this wiki locally