Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3ea12ac

Browse files
implementation of finding minimum elements stack.
1 parent 70584a2 commit 3ea12ac

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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("\nEnter the size of Stack : ");
13+
int sizeOfStack = scInpObj.nextInt();
14+
System.out.println("\nEnter the stack elements : ");
15+
firstStack = new Stack<>();
16+
tempStack = new Stack<>();
17+
pushElementsIntoStack(sizeOfStack);
18+
System.out.println("\nInput Stack : " + firstStack);
19+
System.out.println("\nPush elements to stack using custom temp stack : ");
20+
int noOfNewItems = scInpObj.nextInt();
21+
for (int i=0;i<noOfNewItems;i++) {
22+
System.out.print("\npush the element No " + (i + 1) + " : ");
23+
customPush(scInpObj.nextDouble());
24+
}
25+
customPop();
26+
customPop();
27+
customPush(1000.300);
28+
System.out.println("\nFinal updated stack post push,pop operation : "+firstStack);
29+
System.out.println("\nMinimum 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("\npush the element No " + (i + 1) + " : ");
57+
firstStack.push(scInp1Obj.nextDouble());
58+
}
59+
}
60+
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /