Stacks
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.add(10);// Both add and push does the same thing
stack.pop();// return the value and pops the top
if (!stack.isEmpty());
stack.peek();// Return the top
Stacks
Stacks print in an [a, b, c] format from bottom to top
Balanced Parenthesis
Push on opener and pop on closers.
/* If the String is odd lenght, the return false*/
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char curr = str.charAt(i);
// Push on Openers
if (curr == '(' || curr == '[' || curr == '{') {
stack.push(curr);
} else { // pop on similar CLOSURES
// ALSO CHECK IF SIMIAR IS COMING OUT
char top = stack.peek();//top element of stack
//System.out.println(top);
if ( ((top == '(') && (curr == ')')) ||
((top == '{') && (curr == '}')) ||
((top == '[') && (curr == ']'))
) {
stack.pop();
} else {
return false;
}
}
}
// return (stack.empty());
return true;
Find minimum in a Stack
Maintain 2 Stacks, One internally for keeping track of the Max/Min Stack