Watch java videos

Data Structure is a way to collect and organize data in such a way that we can perform operations on these data in an effective way.
It is a way to store and organize data so that it can be used efficiently. In computer science, it is a data organization, management, and storage format that enables efficient access and modification.

In this post we will discuss the stack data structure. A stack data structure follows the LIFO(Last In Last Out) principal. In a stack the elements are inserted and deleted from the same end. A stack is a data structure where the element that is inserted the last is removed the first. The end from where the elements are removed is called top.
Push: When an element is inserted in the stack, it is called push.
Pop: When an element is removed from the stack, this process is called pop.
Applications of stack: Stack is used to evaluate prefix, postfix and infix expressions, in memory management and in recursion.

Data Structure
import java.io.*;
class Stack
{
static int ST[],size,top;
Stack()
{
size=0;
top=-1;
}
Stack(int cap)
{
size=cap;
ST=new int[size];
top=-1;
}
static void push(int n)
{
if(top==size-1)
{
 System.out.println("Overflow");
}
else
{
top+=1;
ST[top]=n;
}
}
static int pop()
{
if(top==-1)
{
System.out.println("underflow");
return -999;
}
else
{
int val=ST[top];
top=top-1;
return val;
}
}
static void display()
{
 if(top==-1)
{
System.out.println("The stack is empty");
}
else
{
System.out.println("Elements in the stack are:");
for(int i=top;i>=0;i--)
{
System.out.println(ST[i]);
}
}
}
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a size of the stack"); int siz=Integer.parseInt(br.readLine()); Stack obj=new Stack(siz); int k=1;
while (k!=0)
{
System.out.println("Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit");
int ch=Integer.parseInt(br.readLine());
k=ch;
switch(ch)
{
case 1:
System.out.println("Enter value to be inserted");
int n=Integer.parseInt(br.readLine());
push(n);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you");
break;
default:
System.out.println("Invalid input");
break;
}
}
}
}

Output:
Enter a size of the stack
1
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit 1
Enter value to be inserted
22
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit 1
Enter value to be inserted
4
Overflow
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit 2
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit
2
underflow
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit 3
The stack is empty
Enter 1 for Insertion, 2 for deletion ,3 for display,0 for exit 0

Inheritance in java

LEAVE A REPLY

Please enter your comment!
Please enter your name here