Stacks

1 minute read

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 print in an [a, b, c] format from bottom to top

Stacks using 2 queues
class MyStack {
    Queue<Integer> q;
    Queue<Integer> temp;

    public MyStack() {
        //Keep the top element inone of the q, and on pop, move all but one into another
        q = new LinkedList<>();
        temp = new LinkedList<>();
    }
    
    public void push(int x) {        
        q.add(x);
    }
    
    public int pop() {
        while(q.size()!=1){//DO NOT USE for loop as poll redices the size
            temp.add(q.poll());
        }//Leaving only one element n the queue, making it the first
        int ret = q.poll();
        while(!temp.isEmpty()){
            q.add(temp.poll());//Putting everything back
        }
        return ret;
    }
    
    public int top() {
        while(q.size()!=1){
            temp.add(q.poll());
        }//Leaving only one element n the queue, making it the first
        int ret = q.peek();
        temp.add(q.poll());
        while(!temp.isEmpty()){
            q.add(temp.poll());// making the last elemnet of the queue to be the first
        }
        return ret;
    }
    
    public boolean empty() {
        return q.isEmpty() && temp.isEmpty();
    }
}

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