0% found this document useful (0 votes)
5 views5 pages

Java Custom Stack Implementation

The document contains a Java implementation of a custom stack with basic operations such as push, pop, display, and peek. It defines an interface for stack operations and a class that implements these operations, including error handling for stack overflow and underflow. A main method provides a menu-driven interface for users to interact with the stack functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Java Custom Stack Implementation

The document contains a Java implementation of a custom stack with basic operations such as push, pop, display, and peek. It defines an interface for stack operations and a class that implements these operations, including error handling for stack overflow and underflow. A main method provides a menu-driven interface for users to interact with the stack functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

*;
import [Link].*;

interface StackOperations
{
void push(int item);
int pop();
void display();
int peek();
}

class CustomStack implements StackOperations


{
int size;
int[] st;
private int top;
public CustomStack(int max)
{
size=max;
st=new int[size];
top=-1;
}
public void push(int item)
{
try
{
top=top+1;
st[top]=item;
}
catch(Exception e)
{
[Link]("Stack full!! cannot insert element");
top--;
}
}
public int pop()
{
int item;
try{
item=st[top];
top--;
return item;
}
catch (Exception e)
{
[Link]("Stack empty!! cannot pop element");
return -1;
}
}
public void display()
{
[Link]("Stack contains");
for(int i=top;i>=0;i--)
{
if(top==-1)
{
[Link]("Stack empty");
}
else if(top==(size-1))
{
[Link]("Stack full!!");
}
else
{
[Link](" "+st[i]);
}
}

}
public int peek()
{
return st[top];
}
}

class StackTest
{
public static void main(String[] args)
{
char ch='n';
Scanner in =new Scanner([Link]);
CustomStack obj =new CustomStack(10);
do
{
[Link]("Menu");
[Link]("******************************");
[Link]("1. push");
[Link]("2. pop");
[Link]("3. Display");
[Link]("4. peek");
[Link]("5. exit");
[Link]("Enter your choice");
int ipt=[Link]();
switch(ipt)
{
case 1:
{
[Link]("Enter the element");
int ip=[Link]();
[Link](ip);
[Link]();
break;
}
case 2:
{
[Link]("The popped element is:"+[Link]());
break;
}
case 3:
{
[Link]();
break;
}
case 4:
{
[Link]("The top most element is:"+[Link]());
break;
}
default:
{
[Link]("Invalid!!"+"Enter the choice from 1 to 4");
break;
}
}
[Link]("Do you want to continue? (y/n)");
ch=[Link]().charAt(0);
} while(ch=='y');
}
}

Output:

You might also like