Java Program to perform Stack operations like Push, Pop, Peep, Change, Write a java Program for stack using constructor, define methods with parameter etc
Programclass stack
{
int stck[] = new int[10];
int top;
stack() //Default Constructor
{
top=-1;
}
void push(int item)
{
if(top==9)
System.out.println("Stack is Overflow");
else
top++;
stck[top]=item;
}
int pop()
{
if(top<0)
{
System.out.println("Stack is Underflow");
return 0;
}
else
{
return stck[top--];
}
}
void peep(int l)
{
if(top-l+1<=0)
System.out.println("Stack Underflow");
else
System.out.println(" The value of "+l+" location in stack::"+stck[top-l+1]);
}
void change(int l,int x)
{
if(top-l+1<=0)
System.out.println("Stack Underflow");
else
stck[top-l+1]=x;
}
}
class MyStack
{
public static void main(String args[])
{
stack Mystack1 = new stack();
stack Mystack2 = new stack();
//Push
for(int i=0;i<10;i++)
Mystack1.push(i);
for(int i=10;i<20;i++)
Mystack2.push(i);
//Peep Operation
Mystack1.peep(5);
Mystack2.peep(4);
//Change Operation
Mystack1.change(5,25);
Mystack2.change(4,50);
//Peep Operation
Mystack1.peep(5);
Mystack2.peep(4);
//Pop
System.out.println("Stack in Mystack1");
for(int i=0;i<10;i++)
System.out.println(Mystack1.pop());
System.out.println("Stack in Mystack2");
for(int i=0;i<10;i++)
System.out.println(Mystack2.pop());
}
}
No comments:
Post a Comment