OneCompiler

stackk01

1625

package appu2;
import java.util.Scanner;
public class stack {
int s,top,stk[];
public stack(int capacity)
{
s=capacity;
top=-1;
stk=new int[s];
}
public void push(int e)
{
if(top==s-1)
System.out.println("Stack is full,books cannot be added");
else
{
stk[++top]=e;
System.out.println("Book number : "+e+" added");
}
}
public void display()
{
if(top==-1)
System.out.println("No stack of books");
else
{
for(int i=top;i>-1;i--)
System.out.print(stk[i]+" ");
System.out.println();
}
}
public void peek()
{
if(top==-1)
System.out.println("No stack of books");
else
System.out.println("The topmost book number is : "+stk[top]);
}
public int pop()
{
if(top==-1)
return -1;
else
{
int e=stk[top];
top--;
return e;
}
}
public void stacksize()
{
System.out.println("No of books in stack is : "+(top+1));
}
public static void main(String[] args)
{
int size,ele,ch;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of stack : ");
size=sc.nextInt();
stack obj=new stack(size);
System.out.println("1. Push \n 2. Pop \n 3. Book Numbers \n 4. Topmost Book Number \n 5. Number of Books \n 6.Exit");
while(true)
{
System.out.println("Enter your choice");
ch=sc.nextInt();
switch(ch)
{
case 1: System.out.println("Enter the Book number to insert : ");
ele = sc.nextInt();
obj.push(ele);
break;
case 2: ele=obj.pop();
if(ele==-1)
System.out.println("There are no books in the stack");
else
System.out.println("Deleted book number is :"+ele);
break;
case 3: System.out.println("Book numbers in the stack are: ");
obj.display();
break;
case 4: obj.peek();
break;
case 5: obj.stacksize();
break;
case 6: System.exit(1);
default: System.out.println("Enter the right option");
}
}
}
}