Java Tutorial
Last in first out.
Push - inserts element at the top.
Pop - removes element at the top.
import java.util.*; class Jstack { int top=-1; int i; public int n; public int []a; Scanner sc=new Scanner(System.in); public void init() { System.out.println("Enter the stack size: "); n=sc.nextInt(); a=new int[n]; } void push() { if(top==n-1) System.out.println("Stack is full"); else { System.out.println("Enter the element: "); a[++top]=sc.nextInt(); } } void pop() { if(top==-1) System.out.println("Stack is empty"); else System.out.println("Deleted element: " +a[top--]); } void display() { if(top==-1) System.out.println("Stack is empty"); else { System.out.println("Elements: "); for(i=top;i>=0;i--) { System.out.println(a[i]); } } } } class Stack { public static void main(String args[]) { Jstack s=new Jstack(); int opt; s.init(); Scanner sc=new Scanner(System.in); while(true) { System.out.println("Stack:"); System.out.println("\n1.push\n2.pop \n3.display \n4.exit"); System.out.println("Enter option:"); opt=sc.nextInt(); switch(opt) { case 1: s.push(); break; case 2: s.pop(); break; case 3: s.display(); break; case 4: System.exit(0); default: System.out.println("invalid choice"); break; } } } }Output:
D:\Java_Programs>javac Stack.java D:\Java_Programs>java Stack Enter the stack size: 4 Stack: 1.push 2.pop 3.display 4.exit Enter option: 1 Enter the element: 2 Stack: 1.push 2.pop 3.display 4.exit Enter option: 1 Enter the element: 6 Stack: 1.push 2.pop 3.display 4.exit Enter option: 1 Enter the element: 8 Stack: 1.push 2.pop 3.display 4.exit Enter option: 2 Deleted element: 8 Stack: 1.push 2.pop 3.display 4.exit Enter option: 3 Elements: 6 2 Stack: 1.push 2.pop 3.display 4.exit Enter option: 4
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page