Java Program Showing Stack using Array

 Stack is a linear data structure – it is linear in the vertical.

Here are some important points about Stack DS

 It represents a linear collection which is visualized in the vertical

 Bottom end of the stack is fixed.

Top end of the stack is operational.

 Process of adding a node in the collection represented by stack is called ‘PUSH’ operation.

Process of deleting a node from the collection represented by stack is called ‘POP’ operation.

Node PUSH-ed last is POP-ed first. Stack follows LIFO (Last In First Out) protocols in both PUSH and POP processes and in the implementations of its both size related specifications.

//Program demonstrating Stack in Java

StackDemo.java


//Program demonstrating Stack in Java

class Stack
{
	private int tos;
	private int stk[];

	Stack(int size)
	{
		tos=-1;
		stk=new int[size];
	}

	void push(int item)
	{
		if(tos==stk.length-1)
			System.out.println("Stack is Full");
		else
		{
			stk[++tos]=item;
			System.out.println(stk[tos]);
		}
	}

	int pop()
	{
		if(tos<0)
		{
			System.out.println("Stack Underflow");
			return 0;
		}
		else
			return stk[tos--];
	}

}

class StackDemo
{
	public static void main(String[] args)
	{
		Stack s1 = new Stack(5);

		System.out.println("Data Pushed is : ");
		for(int i=0; i<5; i++)
			s1.push(i);

		System.out.println("\nData Popped is : ");
		for(int i=0; i<5; i++)
		System.out.println(s1.pop());

	}
}

Screenshot of the o/p

StackDemo

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s