IMPLEMENTATION OF STACK
ADT
AIM:
To write a java program to implement
stack ADT using interface.
ALGORITHM:
1 .Define an interface mystack with the
required data members and methods
2 .Implement a class stack from mystack.
3. Define push function as public and push the
input elements into the top of the stack.
4. In the pop function check if the stack is
empty ,if not delete the element at top.
5. In the peek function show the popped
element.
6. Define display() to show all the elements
in the stack.
7. In the main function, create the menu with
options.
8. Using switch case call the corresponding
function and perform the required operations.
PROGRAM:
import java.lang.*;
import java.lang.*;
import java.io.*;
import
java.util.*;
interface
Mystack
{
int n=10;
public void pop();
public void push();
public void peek();
public void display();
}
class stack
implements Mystack
{
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
DataInputStream dis=new
DataInputStream(System.in);
if(top==(n-1))
{
System.out.println("Overflow");
return;
}
else
{
System.out.println("Enter element");
int
ele=Integer.parseInt(dis.readLine());
stack[++top]=ele;
}
}
catch(Exception e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Underflow");
return;
}
else
{
int popped=stack[top];
top--;
System.out.println("Popped element"+popped);
}
}
public void peek()
{
if(top<0)
{
System.out.println("Underflow");
return;
}
else
{
int popped=stack[top];
System.out.println("element at top"+popped);
}
}
public void display()
{
if(top<0)
{
}
else
{
String str="
";
for(int i=0;i<=top;i++)
str=str+"
"+stack[i];
System.out.println("Elements are"+str);
}
}
}
class stackadt
{
public static void main(String arg[])throws
IOException
{
DataInputStream dis=new
DataInputStream(System.in);
stack stk=new stack();
int ch=0;
do
{
System.out.println("Enter ur choice \n1.Push
\n2.Pop\n 3.Peek\n 4.Display
5.Exit”);
ch=Integer.parseInt(dis.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.peek();
break;
case 4:
stk.display();
break;
case 5:
System.exit(0);
}
}while(ch<=5);
}
}
OUTPUT
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
1
Enter element
1
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
1
Enter element
3
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
4
Elements
are 1 3
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
2
Popped element3
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
3
element at top1
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
4
Elements
are 1
Enter ur choice
1.Push
2.Pop
3.Peek
4.Display
5.Exit
5
RESULT:
Thus the java program for stack ADT using interface was implemented.
Thus the java program for stack ADT using interface was implemented.
No comments:
Post a Comment