Stack Java

Stack Introduction and Implementation in Java

Stack is more abstract entity than array and many other data structures. The underlying mechanism used to implement stacks is not visible to the user.

It follows Last In First Out (LIFO) principle i.e., stacks allows access to only one data item at a time, that is inserted last. If you remove the last item then you can access the next item that is next to that last item inserted.

Stack operations

  • Push – Adds an item to the collection.
  • Pop – Removes the most recently added item from the collection.

Applications of stack

  • Most microprocessor uses stack based architecture. The stack operations are built into the microprocessor.
  • Old pocket calculators used stack based architecture.

Stack Implementation in Java

The following program implements a stack in java using a class called MyStack.

package com.sneppets.dsalgo;

class MyStack
{
	//max stack array size
	private int maxStackArraySize;
	
	//stack array
	private long[] myStackArray;
	
	//stack top
	private int top;
	
	//constructor
	public MyStack(int size)
	{
		//set stack array size
		maxStackArraySize = size;
		//create array
		myStackArray = new long[maxStackArraySize];
		//no elements in the stack array yet
		top = -1;
	}
	
	public void push(long element)
	{
		//increment top and insert the element in top of the stack array
		myStackArray[++top] = element;
	}
	
	public long pop()
	{
		//access the element from the top of the stack array
		return myStackArray[top--];
	}
	
	public long peek()
	{
		//peek at the top of the stack array
		return myStackArray[top];
	}
	
	public boolean isEmpty()
	{
		//return true is stack array is empty
		return (top == -1);
	}
	
	public boolean isFull()
	{
		//return true if stack array is full
		return (top == maxStackArraySize-1);
	}
	
}
/*
 * author: sneppets.com
 */
public class StackExample {
	
	public static void main (String[] args)
	{
		//create new stack
		MyStack myStack = new MyStack(5);
		
		//push elements on to your new stack
		myStack.push(3);
		myStack.push(5);
		myStack.push(7);
		myStack.push(9);
		
		//delete elements from stack until the stack is empty
		while( !myStack.isEmpty())
		{
			long element = myStack.pop();
			System.out.println(element);
			
		}
		
		
	}

}

Output

9
7
5
3

Recommended Posts

Reference

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments