Data structure java version queue

content

A brief introduction to the knowledge related to queues

1. What is a queue

2. Ordinary queues and double-ended queues

3. Implementation of some operations on the queue

4. Circular queue

2. Analysis of related topics

1. Design a circular queue

2. Implement a stack with a queue

3. Implement queues with stacks


A brief introduction to the knowledge related to queues

The basic concept of queue:

1. What is a 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 (First In First Out) Entry queue: the end of the insertion operation is called the tail of the queue ( Tail/Rear ) Out of the queue: the end of the deletion operation is called the head of the queue ( Head/Front )

2. Ordinary queues and double-ended queues

3. Implementation of some operations on the queue

①Ordinary queue

Queue (generally use the processing of returning special values, which is more convenient)

error handling Throw an exception return special value
enqueue add(e) offer(e)
dequeue remove() poll()
head element element() peak()

Simple code example:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(1);
        queue.offer(2);
        System.out.println("该队列队头元素为:");
        System.out.println(queue.peek());
        System.out.println("出队元素为");
        System.out.println(queue.poll());
    }
}

②Double-ended queue

Deque (generally use the processing of returning special values, which is more convenient)

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Deque<Integer> queue = new LinkedList<>();
      queue.offerFirst(2);
      queue.offerLast(1);
        System.out.println("该队列队头元素为:");
        System.out.println(queue.peek());
        System.out.println("出队元素为");
       System.out.println(queue.poll());
    }
}

 Implement a queue with a singly linked list: 

 Code:

class Node{
    public int val;
    public Node next;
    public Node(int val){
        this.val=val;
    }
}
//实质上是一个尾插法
public class MyQueue {
    public Node head;
    public Node last;
    public void offer(int val){
        Node node=new Node(val);
        if(head==null){
            head=node;
            last=node;
        }
        last.next=node;
        last=last.next;
    }
    //出队
    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("队列为空!");
        }int oldVal=head.val;
        this.head=head.next;
        return oldVal;
    }
    public boolean isEmpty(){
        return this.head==null;
    }
    //查看栈顶元素
    public int peek( ){
        if(isEmpty()) {
            throw new RuntimeException("队列为空!");
        }
        return head.val;
    }
    }

4. Circular queue

①Introduction of circular queue


 

 

2. Analysis of related topics

1. Design a circular queue

622. Design Circular Queue - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/design-circular-queue/Problem-solving ideas: see Circular Queue and the following figure 

Code:

class MyCircularQueue {
    public int[]elem;
    public int front;//队头下标
    public int rear;//队尾下标
    public MyCircularQueue(int k) {
 this.elem=new int[k+1];
    }
//入队操作
    public boolean enQueue(int value) {
        if(isFull()) return false;
        this.elem[rear]=value;
        rear=(this.rear+1)%elem.length;
        return true;
    }
    //出队操作
    public boolean deQueue() {
        if(isEmpty()) return false;
        //不用管原数,会被新入队的数直接替代
        front=(this.front+1)% elem.length;
        return true;
    }
//得到队头元素
    public int Front() {
     if(isEmpty()) {
         throw new RuntimeException("队列为空");//OJ上改为return -1;
     }
        return this.elem[front];
    }
//得到队尾元素
    public int Rear() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空");//OJ上改为return -1;
        }
        int index=0;
        if(rear==0){
            index=elem.length-1;
        }else{index=rear-1;}
        return this.elem[index];
    }

    public boolean isEmpty() {
     return front==rear;
    }

    public boolean isFull() {
        //判断rear下一个是front就是满了
    if((this.rear+1)% elem.length==front){
        return true;
    }
    return false;
    }
}

2. Implement a stack with a queue

225. Implementing stacks with queues - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/implement-stack-using-queues/

 Problem solving ideas:

①When pushing into the stack, enter a queue that is not empty, and it is empty at the beginning to specify a queue

② When popping the stack, find a queue that is not empty, and pop size-1 elements to another queue, and the remaining element is the popped element

code show as below:

class MyStack {
    //创建两个队列
    private Queue<Integer> qu1;
    private Queue<Integer> qu2;

    public MyStack() {
        //初始化两个队列
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }

    public void push(int x) {
        //哪个队列不为空,入到哪个队列里,均为空,随便入一个队列,此处入的是qu1
        if (!qu1.isEmpty()) {
            qu1.offer(x);
        } else if (!qu2.isEmpty()) {
            qu2.offer(x);
        } else {
            qu1.offer(x);
        }
    }
    public int pop() {
        if (empty()) return -1;
        if (!qu1.isEmpty()) {
            int size = qu1.size();
            for (int i = 0; i < size - 1; i++) {
                //需要拿一个中间值接收一下暂时出队的元素
                //将出队元素放入另一个队中
                int val = qu1.poll();
                qu2.offer(val);
            }
            return qu1.poll();
        }
        if (!qu2.isEmpty()) {
            int size = qu2.size();
            for (int i = 0; i < size - 1; i++) {
                //需要拿一个中间值接收一下暂时出队的元素
                //将出队元素放入另一个队中
                int val = qu2.poll();
                qu1.offer(val);
            }
            return qu2.poll();
        }
        return -1;
    }
    //得到队头元素
    public int top() {
        if (empty()) return -1;
        if (!qu1.isEmpty()) {
            //因为后续部分要用到val,所以必须拿出pop中局部变量的位置到前面
            int val = -1;
            int size = qu1.size();
            for (int i = 0; i < size; i++) {
                //需要拿一个中间值接收一下暂时出队的元素
                //将出队元素放入另一个队中
                val = qu1.poll();
                qu2.offer(val);
            }
            return val;
        }
        if (!qu2.isEmpty()) {
            int val = -1;
            int size = qu2.size();
            for (int i = 0; i < size; i++) {
                //需要拿一个中间值接收一下暂时出队的元素
                //将出队元素放入另一个队中
                val = qu2.poll();
                qu1.offer(val);
            }
            return val;
        }
        return -1;
    }
 
    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty(); 
    }
}

3. Implement queues with stacks

232. Implementing Queues with Stacks - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/implement-queue-using-stacks/Problem-solving ideas:

 code show as below:

class MyQueue {
    public Stack<Integer>stack1;
    public Stack<Integer>stack2;
    public MyQueue() {
        stack1=new Stack();
        stack2=new Stack();
    }
    //出队第一个栈
    public void push(int x) {
 stack1.push(x);
    }
    public int pop() {
if(empty()) return -1;
if(stack2.isEmpty()){
    while(!stack1.isEmpty()){
    stack2.push(stack1.pop());
}
}
   return stack2.pop();
}
    
    public int peek() {
if(empty()) return -1;
if(stack2.isEmpty()){
    while(!stack1.isEmpty()){
    stack2.push(stack1.pop());
}
}
   return stack2.peek();
}
    
    public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/122524436