Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class stac{
- public static void main(String Args[])
- {
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter stack size : ");
- stack_maker st = new stack_maker(sc.nextInt());
- while(true)
- {
- System.out.println("\n1. Push\n2. Pop\n3. Peek\n4. Display\n5. New Stack\n6. Exit");
- System.out.print("\nEnter your choice : ");
- switch(sc.nextInt())
- {
- case 1:
- System.out.print("\n\tEnter no. to Push : ");
- st.Push(sc.nextInt());
- break;
- case 2:
- st.Pop();
- break;
- case 3:
- st.Peek();
- break;
- case 4:
- st.Display();
- break;
- case 5:
- System.out.print("\n\tThe prervios stack will be lost. Continue(y/n)?");
- if(sc.next().toLowerCase().charAt(0) == 'y')
- {
- System.out.print("\n\tEnter new stack size : ");
- st = new stack_maker(sc.nextInt());
- }
- break;
- case 6:
- st.finalize();
- return;
- }
- System.out.println();
- }
- }
- }
- class stack_maker {
- private int[] stack;
- private int top, size;
- stack_maker(int size)
- {
- top = -1;
- this.size = size;
- stack = new int[size];
- System.out.println("New stack of size "+ size +" created\n");
- }
- private boolean isFull()
- {
- if(top == size-1)
- return true;
- return false;
- }
- private boolean isEmpty()
- {
- if(top == -1)
- return true;
- return false;
- }
- public void Push(int n)
- {
- if(isFull())
- {
- System.out.println("\nStack Overflow!");
- return;
- }
- System.out.println("\n" + n + " added in stack");
- stack[++top] = n;
- }
- public void Pop()
- {
- if(isEmpty())
- {
- System.out.println("\nEmpty stack, can't pop!");
- return;
- }
- System.out.println("\n"+stack[top--]+ " was popped");
- }
- public void Peek()
- {
- if(isEmpty())
- {
- System.out.println("\nEmpty stack, can't peek!");
- return;
- }
- System.out.println("\nElement at the top is : " + stack[top]);
- }
- public void Display()
- {
- if(isEmpty())
- {
- System.out.println("\nEmpty Stack, nothing to display!");
- return;
- }
- System.out.println("\n\n");
- for(int i = top; i >= 0; i--)
- System.out.println("|\t"+stack[i]+"\t|\n-----------------");
- }
- protected void finalize()
- {
- System.out.println("BYE!");
- System.gc();
- }
- }
Add Comment
Please, Sign In to add comment