Thursday, February 4, 2021

Stack Implementation using Array Data structure


Stack Implementation

import java.util.Arrays;
public class Stack {

	private int count=0;
	private T[] data;
	
	Stack(){
		data = (T[]) new Object[1];
	}
	
	public int size() {
		return count;
	}
	public boolean isEmpty() {
		return count==0;
	}
	public void push(T newItem) {
		
		if(count==data.length) {
			resize(2*data.length);
		}
		data[count++] = newItem;
	}
	public T pop() {
		T item = data[--count];
		if(count>0 && count == (data.length/4)){
			resize(data.length/2);
		}
		return item;
	}
	public void resize(int newCapacity){
		T stackCopy[] = Arrays.copyOf(data, newCapacity);
		data = stackCopy;
	}
}



App Runner:-


public class StackApp {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Stack stack = new Stack();
		stack.push(10);
		stack.push(30);
		stack.push(4);
		stack.push(7);
		stack.push(14);
		
		while(!stack.isEmpty())
			System.out.println(stack.pop());
	}

}


Output:-
14
7
4
30
10

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...