import java.util.*; public class GenStackAL<T> { ArrayList<T> stack; GenStackAL(ArrayList<T> stack){ this.stack=stack; } void push(T a){ stack.add(a); } T pop(){ if(stack.size()==0){ return null; } else{ T i= stack.remove(stack.size()-1); return i; } } void display(){ if(stack.size()==0){ System.out.println("Stack is empty"); } else{ for(int i=stack.size()-1;i>=0;i--){ System.out.println(stack.get(i)); } } } public static void main(String args[]){ Scanner sc= new Scanner(System.in); ArrayList<Integer> a= new ArrayList<>(); GenStackAL<Integer> s1= new GenStackAL<>(a); int op=0; Integer ele; System.out.println("1.push\n2.pop\n3.Display\n4.Exit"); while(op!=4){ System.out.print("Enter option: "); op=sc.nextInt(); switch(op){ case 1: System.out.println("enter element to push: "); ele = sc.nextInt(); s1.push(ele); break; case 2: ele=s1.pop(); if(ele==null){ System.out.println("Stack is empty"); } else{ System.out.println("Poped element:"+ele); } break; case 3: s1.display(); break; case 4: return; default : System.out.println("Enter valid option"); } } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter