-
Notifications
You must be signed in to change notification settings - Fork 0
/
IfExistsInStack.java
49 lines (42 loc) · 1.1 KB
/
IfExistsInStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Find if a given number N exists in a stack S.
*/
package stack;
import java.util.Stack;
import static util.Utils.createStack;
import static util.Utils.printInput;
/**
* @author mandeep
*/
public class IfExistsInStack {
public static void main(String args[]) {
int target = 2;
Stack<Integer> stack = createStack();
printInput(ifExistsInStack(target, stack));
printInput(ifExistsInStack(target, null));
printInput(ifExistsInStack(target, new Stack<>()));
}
/**
* Time: O(n)
* Space: O(1)
*
* @param target
* @param stack
* @return
*/
private static boolean ifExistsInStack(int target, Stack<Integer> stack) {
if (stack == null || stack.isEmpty()) {
return false;
}
Stack<Integer> temp = new Stack<>();
boolean found = false;
while (!stack.isEmpty()) {
if (stack.peek() == target) {
found = true;
break;
}
temp.push(stack.pop());
}
return found;
}
}