1
+ package com .udemy .dsapart1 .stacks ;
2
+ import java .util .Scanner ;
3
+ import java .util .Stack ;
4
+
5
+ public class FindMinimumElementFromStack {
6
+
7
+ static Stack <Double > firstStack ;
8
+ static Stack <Double > tempStack ;
9
+
10
+ public static void main (String [] args ) {
11
+ Scanner scInpObj = new Scanner (System .in );
12
+ System .out .print ("\n Enter the size of Stack : " );
13
+ int sizeOfStack = scInpObj .nextInt ();
14
+ System .out .println ("\n Enter the stack elements : " );
15
+ firstStack = new Stack <>();
16
+ tempStack = new Stack <>();
17
+ pushElementsIntoStack (sizeOfStack );
18
+ System .out .println ("\n Input Stack : " + firstStack );
19
+ System .out .println ("\n Push elements to stack using custom temp stack : " );
20
+ int noOfNewItems = scInpObj .nextInt ();
21
+ for (int i =0 ;i <noOfNewItems ;i ++) {
22
+ System .out .print ("\n push the element No " + (i + 1 ) + " : " );
23
+ customPush (scInpObj .nextDouble ());
24
+ }
25
+ customPop ();
26
+ customPop ();
27
+ customPush (1000.300 );
28
+ System .out .println ("\n Final updated stack post push,pop operation : " +firstStack );
29
+ System .out .println ("\n Minimum peeked element from Stack : " +firstStack .peek ());
30
+ }
31
+
32
+
33
+ private static void customPush (double itemToPush ) {
34
+ firstStack .push (itemToPush );
35
+ if (tempStack .isEmpty ()) {
36
+ tempStack .push (itemToPush );
37
+ } else if (tempStack .peek () > itemToPush ) {
38
+ tempStack .push (itemToPush );
39
+ }
40
+ System .out .println ("\n " +itemToPush +" item pushed to stack" );
41
+ }
42
+
43
+
44
+ private static void customPop () {
45
+ double srcStackPeek = firstStack .peek ();
46
+ System .out .println ("\n " +firstStack .pop ()+" item pop from stack" );
47
+ if (tempStack .peek () == srcStackPeek ) {
48
+ tempStack .pop ();
49
+ }
50
+ }
51
+
52
+
53
+ private static void pushElementsIntoStack (int sizeOfStack ) {
54
+ Scanner scInp1Obj = new Scanner (System .in );
55
+ for (int i = 0 ; i < sizeOfStack ; i ++) {
56
+ System .out .print ("\n push the element No " + (i + 1 ) + " : " );
57
+ firstStack .push (scInp1Obj .nextDouble ());
58
+ }
59
+ }
60
+
61
+ }
0 commit comments