LeetCode stack and queue application——

 What classic problems can stacks and queues solve? Every question can be found on my homepage, welcome everyone to pay attention~~

(1) Bracket matching problem (stack)

(2) String deduplication problem (stack)

  (3) Reverse Polish expression problem (stack)

(4) Sliding window maximum problem (monotonic queue) 

(5) Top K elements with the most occurrences (priority queue)

(6) Stack implementation queue

(7) Queue implementation stack 

1. Solution 

 

class MyStack {

  
    Queue<Integer> queue1; // 和栈中保持一样元素的队列
    Queue<Integer> queue2; // 辅助队列

    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x);
        while(!queue1.isEmpty()){
            queue2.offer(queue1.poll());
        }
         Queue<Integer> queueTemp = queue1;
         queue1 = queue2;
         queue2 = queueTemp;
    }
    
    public int pop() {
        return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {    
        return queue1.isEmpty();
    }
}

2. Basic knowledge of the stack

The most notable feature of the stack is: first in last out

1. Common implementation classes of stacks in Java:

The most basic implementation: Stack<Integer> stack=new Stack<>();

Double-ended queue implementation: Deque<Integer> stack=new LinkedList<>();

2. Common methods of stack

push(x) -- push an element to the tail of the queue.
pop() -- removes an element from the head of the queue.
peek() -- returns the element at the head of the queue.
empty() -- returns whether the queue is empty.

3. Basic knowledge of queues

The most notable feature of the queue is: first in first out

1. Common implementation classes of queues in Java:

Ordinary queue: Queue<Integer> queue=new LinkedList<>();

Double-ended queue: Deque<Integer> queue=new LinkedList<>();

Priority queue: PriorityQueue<Integer> queue=new PriorityQueue<>();

2. Common methods of queues

add Add an element If the queue is full, throw a IIIegaISlabEepeplian exception
remove Remove and return the element at the head of the queue If the queue is empty, throw a NoSuchElementException
element Return the element at the head of the queue If the queue is empty, then Throws a NoSuchElementException

size The number of elements
offer Add an element and return true If the queue is full, return false
poll Remove and return the element at the head of the queue If the queue is empty, return null
peek Return the element at the head of the queue If the queue is empty, return null


put adds an element, blocks if the queue is full
take removes and returns the element at the head of the queue, blocks if the queue is empty

Guess you like

Origin blog.csdn.net/w20001118/article/details/127140364