Stacks and queues of data structures (this is not going to look at it)

stacks and queues

stack

stack concept

Stack: A special linear list that allows insertion and removal of elements only at one fixed end. One end where data insertion and deletion are performed is called the top of the stack, and the other end is called the bottom of the stack. The data elements in the stack follow the LIFO (Last In First Out) principle.
Push stack: The insertion operation of the stack is called push/push/push, and the pushed data is at the top of the stack.
Pop: The deletion of the stack is called pop. The output data is at the top of the stack as shown in the
figure:
when pushing
insert image description here
insert image description here
into the stack: when popping out:
insert image description here
insert image description here

Implementation of stack

There are generally two ways to implement the stack, one is to use the sequence table to implement the other is to implement the linked list. In actual cases, we use the sequence table to implement the stack.

public class MyStack {
    
    
    public int[] elem;
    public int usedSize;
    public MyStack(){
    
    
        this.elem=new int[10];
    }
    //判断栈是否为空
    public boolean isFull() {
    
    
        if(usedSize==this.elem.length){
    
    
            return true;
        }
        return false;
    }
    //将元素插入栈当中
    public void push(int item) {
    
    
        if(isFull()){
    
    
        //如果栈已经填满,则将栈进行2倍扩容
            this.elem= Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize]=item;
        this.usedSize++;
    }
    public boolean empty() {
    
    
    //判断栈是否为空,是则返回true,不是则返回false
        return this.usedSize==0;
    }
    public int pop() throws RuntimeException{
    
    
        if (empty()){
    
    
        //如果栈为空则抛出异常
            throw new RuntimeException("栈空了");
        }
        //返回栈顶元素并从栈中删除栈顶元素
        return this.elem[--this.usedSize];
    }
    public int peek() {
    
    
        if (empty()){
    
    
        //如果栈为空则抛出异常
            throw new RuntimeException("栈空了");
        }
        //返回栈顶元素但不从栈中删除栈顶元素
        return this.elem[this.usedSize-1];
    }
}

Note: In java programs, you can use the stack
format directly:
Stack variable name=new Stack<>()

method explain
E push(E item) push the stack
E pop() pop
E peek() View the top element of the stack
boolean empty() Check if the stack is empty

stack interview questions

bracket matching

insert image description here
Solution:
This question tests the mastery of the stack. In order to match valid parentheses, we can use a stack, put the left parentheses encountered into the stack, and take out the top element of the stack when encountering the right parenthesis for comparison, and delete if it matches. The top of the stack, if it does not match, it will return false; after the loop is over, it will be judged whether the stack is empty, if it is empty, it will return true, otherwise it will return false;

class Solution {
    
    
    public boolean isValid(String s) {
    
    
        Stack<Character> stack=new Stack<>();
        char[] ch=s.toCharArray();
        for(char ch1:ch){
    
    
            switch(ch1){
    
    
                case '(':
                case '{':
                case '[':
                stack.push(ch1);
                break;
                case ')':
                if(!stack.isEmpty()&&stack.peek()=='('){
    
    
                    stack.pop();
                }
                else{
    
    
                    return false;
                }
                break;
                case ']':
                if(!stack.isEmpty()&&stack.peek()=='['){
    
    
                    stack.pop();
                }
                else{
    
    
                    return false;
                }
                break;
                case '}':
                if(!stack.isEmpty()&&stack.peek()=='{'){
    
    
                    stack.pop();
                }
                else{
    
    
                    return false;
                }
                break;
            }
        }
        if(stack.isEmpty()){
    
    
            return true;
        }
        return false;
    }
}

insert image description here

Reverse Polish Expression Evaluation

insert image description here
This question tests our familiarity with the prefix algorithm and the infix algorithm. We use a stack and put numbers into it. When encountering '+', '-', '*', '/', take out the top two of the stack. element, operate with the corresponding operator, and
then put the newly obtained number on the stack.

class Solution {
    
    
    public int evalRPN(String[] tokens) {
    
    
        Stack<Integer> stack = new Stack<>();
        int n = tokens.length;
        for (String token:tokens) {
    
    
            if (isNumber(token)) {
    
    
                stack.push(Integer.parseInt(token));
            } else {
    
    
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch (token) {
    
    
                    case "+":
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                    default:
                    break;
                }
            }
        }
        return stack.pop();
    }
    public boolean isNumber(String token) {
    
    
        return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token));
    }
}

insert image description here

queue

queue concept

Queue: A special linear table that only allows data insertion operations at one end and deletion data operations at the other end. The queue has a first-in-first-out (FIFO) (First In First Out) entry queue: The end of the insertion operation is called the tail (Tail/ Rear) out of the queue: the end of the deletion operation is called the head of the queue (Head/Front). As shown in the
figure:
insert description in picture here
in order to implement the queue, the structure of an array and a linked list can be used, and it is better to use the structure of a linked list, because if the structure of an array is used , dequeue data at the head of the array, the efficiency will be relatively low.

class Node {
    
    
    public int data;
    public Node next;
    public Node(int data) {
    
    
        this.data = data;
    }
}
public class MyQueueLinked {
    
    
    private Node front;
    private Node rear;
    private int usedSize;
    //插入元素进入队列中
    public void offer(int val) {
    
    
        Node node=new Node(val);
        if (front==null){
    
    
            this.front=node;
            this.rear=node;
        }
        else {
    
    
            this.rear.next=node;
            this.rear=node;
        }
        this.usedSize++;
    }
    public int size() {
    
    
        return this.usedSize;
    }
    public boolean isEmpty() {
    
    
        return this.usedSize == 0;
    }
    //返回栈头元素,并从队列中删除
    public int poll() {
    
    
        if (isEmpty()) {
    
    
            throw new RuntimeException("队列为空!");
        }
        int val=this.front.data;
        if(this.front.next == null) {
    
    
            this.front = null;
            this.rear = null;
        }
        else {
    
    
            this.front=this.front.next;
        }
        this.usedSize--;
        return val;
    }
    //返回栈头元素,但不从队列中删除
    public int peek(){
    
    
        if (isEmpty()) {
    
    
            throw new RuntimeException("队列为空!");
        }
        return this.front.data;
    }
}

circular queue

In practice we sometimes also use a queue called a circular queue. Circular queues can be used, for example, when operating system courses explain the producer-consumer model. Circular queues are usually implemented using arrays.

insert image description here
A circular queue is the same as a normal queue: elements are added at the end of the queue, and elements are output at the head of the queue

How to distinguish between empty and full circular queue

The circular queue generally reserves a position to judge whether it is full. As shown in the
figure:
insert image description here
When Q.front==Q.rear, the circular queue is empty at this time.
insert image description here
When (Q.rear+1)% the length of the array = Q.front, the circular queue is full

cohort interview questions

conditional pop

insert image description here
From the question, we can create two queues a, b, one queue a is used to put elements first, and the second queue b is used to store the elements deleted from a and finally return to queue b.

import java.util.*;

public class CatDogAsylum {
    
    
    public ArrayList<Integer> asylum(int[][] ope) {
    
    
        // write code here
        ArrayList<Integer> one=new ArrayList<>();
        ArrayList<Integer> two=new ArrayList<>();
        for (int i = 0; i < ope.length; i++) {
    
    
            if (ope[i][0]==1){
    
    
                one.add(ope[i][0]*ope[i][1]);
            }
            else {
    
    
                if (ope[i][1]==1){
    
    
                    int size= one.size();
                    for(int j=0;j<size;j++){
    
    
                        if(one.get(j)>0){
    
    
                            two.add(one.remove(j));
                            break;
                        }
                    }
                }
                else if(ope[i][1]==0){
    
    
                    two.add(one.remove(0));
                }
                else {
    
    
                    int size= one.size();
                    for(int j=0;j<size;j++){
    
    
                        if(one.get(j)<0){
    
    
                            two.add(one.remove(j));
                            break;
                        }
                    }
                }
            }
        }
        return two;
    }
}

insert image description here

recent requests

insert image description here
This question tests our understanding of the question, which probably means putting t into the queue, and then judging whether the value in the queue is in the interval [t-3000, t]; if there is a value that is not in this range, remove it from the queue Delete from the queue, and finally return how many elements are still in the queue.

class RecentCounter {
    
    
    Queue<Integer> q;
    public RecentCounter() {
    
    
        this.q=new LinkedList<>();
    }
    
    public int ping(int t) {
    
    
        q.add(t);
        while(q.peek()<t-3000){
    
    
            q.poll();
        }
        return q.size();
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_49830664/article/details/120650231