Stacks and queues typical exercise summary

1. Stack implemented with queue

Examples: 12233445566778

Analysis of ideas: the need to realize there are two queues, the stack is the last out, last in first out.
When the queue: ① two queues are empty, the qu1 ② there is a queue is not empty, the team included a non-empty queue.
When the queue: Which out which queue is not empty. An n-1 to another queue, then the last element in the stack.

 

import java.util.LinkedList;
import java.util.Queue;

/**
 * 两个队列实现栈
 */

public class MyStack {

    Queue<Integer> queue1 = new LinkedList<>();
    Queue<Integer> queue2 = new LinkedList<>();
    /** Initialize your data structure here. */
    public MyStack() {
    }

    /** Push element x onto stack. */
    //哪个栈不为空入哪个栈
    public void push(int x) {
        if (!queue1.isEmpty()) {
            queue1.offer(x);
        } else if (!queue2.isEmpty()) {
            queue2.offer(x);
        } else {
            queue1.offer(x);
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        if (!queue1.isEmpty()) {
            int size1 = queue1.size()-1; //由于每次queue1.poll()导致size发生变化,因此要事先保存
            for (int i = 0; i < size1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
        if (!queue2.isEmpty()) {
            int size2 =  queue2.size()-1;
            for (int i = 0; i < size2; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
        return -1;
    }

    /** Get the top element. */
    public int top() {
        if (!queue1.isEmpty()) {
            int size1 = queue1.size(); //由于每次queue1.poll()导致size发生变化,因此要事先保存
            int tmp = 0;  //查看栈顶元素,但是要把元素全部弹入另外一个栈,因为入栈的是非空栈
            for (int i = 0; i < size1; i++) {
                tmp = queue1.poll();
                queue2.offer(queue1.poll());
            }
            return tmp;
        }
        if (!queue2.isEmpty()) {
            int size2 =  queue2.size();
            int tmp = 0;
            for (int i = 0; i < size2; i++) {
                tmp = queue2.poll();
                queue1.offer(queue2.poll());
            }
            return tmp;
        }
        return -1;
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            return true;
        }
        return false;
    }
}

2. Stack queue

Examples: 12233445566778

Analysis of ideas: the need to implement two stacks [first queue stack into the team; the second stack, a team]
stack: ① into stack1
the stack: To a stack1, put all the elements into stack2, then stack2 out of the top element.

 

import java.util.Stack;

class MyQueue {
    public Stack<Integer> stack1;
    public Stack<Integer> stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        if (!stack2.isEmpty()) {  //stack1可能为空
            return stack2.pop();
        }
        return -1;
    }

    /** Get the front element. */
    public int peek() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        if (!stack2.isEmpty()) {  //stack1可能为空
            return stack2.peek();
        }
        return -1;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

3. parentheses matching

"()" "(]" "{[]}" "()[]{}" "([)]" ")))))))))" "(((((((((((("

Analysis of ideas: to have a stack, i traverse the string, if the left bracket, the stack; if it is a right parenthesis, the top element to see if they match.

 

    public  static boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if(ch == '(' || ch == '{'|| ch == '[') {
                stack.push(ch);
            }else {
                if(stack.empty()) {
                    System.out.println("右括号多");
                    return false;
                }
                char top = stack.peek();
                if(top == '(' && ch == ')' ||
                        top == '{' && ch == '}'||
                        top == '[' && ch == ']' ){
                    stack.pop();
                }else {
                    System.out.println("右括号匹配错误!");
                    return false;
                }
            }
        }

        if(!stack.empty()) {
            System.out.println("左括号多!");
            return false;
        }
        return true;
    }

4. The realization of a minimum stack

Examples: 41-382 elements taken from the inside of the stack, the current minimum stack each time to go.

Analysis of ideas: the need for two stacks stack1 minstack, and minstack which put elements are the smallest element in the current stack.
When the stack, first-stack1. minstack If empty, the stack; if not empty, to ensure that the top element is the smallest element in the current stack, if you want to push the elements is larger than the top of the stack, not the stack.
When the stack, and if stack1 minstack top element are the same, while the stack; otherwise, only the elemental stack1 stack.

class MinStack {
        /** initialize your data structure here. */
    public Stack<Integer> stack = new Stack<>();
    public Stack<Integer> MinStack = new Stack<>();

    MinStack() {

    }
    
    void push(int x) {
        stack.push(x);
        if(MinStack.empty()) {
            MinStack.push(x);
        } else {
            int tmp = MinStack.peek();
            if(tmp >= x) {
                MinStack.push(x);
            }
        }
    }
    
    void pop() {
        int tmp = stack.pop();
        if(tmp == MinStack.peek()) {
            MinStack.pop();
        }
    }
    
    int top() {
        return stack.peek();
    }
    
    int getMin() {
        return MinStack.peek();
    }
}

 

Published 51 original articles · won praise 14 · views 2309

Guess you like

Origin blog.csdn.net/qq_41185460/article/details/103563818