Write a java program to implement stack
As we know, Stack is a implementation class of Collection interface and child class of Vector collection.
Stack uses FIFO pattern. To insert element into Stack “push” is use and to remove elements from Stack “pop” is use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); Stack s=new Stack(); while(true) { String str=sc.next(); if(str.equals("push")) { int ele=sc.nextInt(); s.push(ele); } else { s.pop(); } System.out.println(s); } } } |
Output
1 2 3 4 5 6 7 8 |
push 10 [10] push 20 [10, 20] pop [10] |