Quickly master the basics of queues

A queue is a linear data structure that only allows insertion operations on one side (the tail of the queue) and deletion operations on the other side (the head of the queue). The insertion operation is called enqueuing, and the deletion operation is called dequeuing. The queue follows the first-in-first-out (FIFO) principle, that is, the elements at the head of the queue are deleted first, and the elements at the end of the queue are deleted last.

Insert image description here

Queue characteristics

  1. First in, first out: The elements in the queue are taken out in the order they enter the queue, that is, the element that enters the queue first will be taken out first.
  2. Limited capacity: Queues usually have a certain maximum capacity. When the queue reaches the maximum capacity, new elements will not be able to enter the queue.
  3. Basic operations: The queue supports two basic operations: insertion (enqueue) and deletion (dequeue). The insertion operation is performed at the tail of the queue, and the deletion operation is performed at the head of the queue.

Implement queue based on linked list

This implementation method is relatively simple, as follows:

public class LinkQueue {
    
    
    // 头节点
    private  Node front;
    //尾节点
    private Node rear;
    //队列大小
    private int size;
    public LinkQueue(){
    
    
        //初始化头节点和尾节点
        this.front = new Node(0);
        this.rear = new Node(0);
    }
    /**
     *入队
     */
    public  void push(int value){
    
    
     //创建新节点
     Node newNode = new Node(value);
      //临时节点指向头节点
      Node temp = front;
      //循环遍历,直到临时节点指向尾节点
      while (temp.next!=null){
    
    
          temp = temp.next;
      }
      //将新节点指向头节点
      temp.next = newNode;
      //将尾节点指向新节点
      rear = newNode;
      //队列大小加1
      size++;
    }
    /**
     * 出队
     */
    public int pull(){
    
    
       //如果队列为空,则提示
       if(front.next==null){
    
    
           System.out.println("队列已经为空!");
       }
       //获取头节点指向的节点
       Node fristNode = front.next;
       //将头节点指向头节点指向的节点的下一个节点
       front.next = fristNode.next;
       //队列大小减1
       size--;
       //返回头节点指向的节点
       return fristNode.data;
    }
    /**
     * 遍历队列
     */
    public  void  traverse(){
    
    
       //临时节点指向头节点指向的节点
       Node temp = front.next;
       //循环遍历,直到临时节点指向尾节点
       while (temp!=null){
    
    
           //输出临时节点指向的节点
           System.out.printf(temp.data+"\t");
           //将临时节点指向临时节点指向的节点的下一个节点
           temp = temp.next;
       }
    }
   //测试方法
    public static void main(String[] args) {
    
    
     //创建一个队列
     LinkQueue linkQueue = new LinkQueue();
     //将1,2,3入队
     linkQueue.push(1);
     linkQueue.push(2);
     linkQueue.push(3);
        //输出第一个出队的元素
        System.out.println("第一个出队的元素为"+linkQueue.pull());
        //输出队列中的元素
        System.out.println("队列中的元素为");
        linkQueue.traverse();

    }

}
class Node{
    
    
    //节点数据
    public  int data;
    //指向下一个节点
    public Node next;
    //构造函数
    public Node(int data){
    
    
        this.data = data;
    }
}

First, a Node class is defined to represent the nodes in the queue. Each node contains a data item and a pointer to the next node.
In the LinkQueue class, three private attributes are defined: front represents the head node of the queue, rear represents the tail node of the queue, and size represents the size of the queue.
The constructor LinkQueue() is used to initialize the queue. It creates a head node and a tail node and makes their values ​​​​0.
The push() method is used for enqueuing operations, that is, adding elements to the queue. It first creates a new node, then traverses the queue through a temporary node until it finds the tail node, links the new node to the tail node, and updates the rear pointer to point to the new tail node. Finally, increase the queue size by 1.
The pull() method is used for dequeuing operations, that is, removing elements from the queue. First check whether the queue is empty. If it is empty, it will prompt that the queue is empty. Then remove the node from the head of the queue, update front to point to the next node, and reduce the queue size by 1. Finally, the value of the removed node is returned.
The traverse() method is used to traverse the queue and print out all elements in the queue.

Implement queue using stack

Using queues to implement stacks will be encountered in many questions, such as question 232:

Implement the MyQueue class:

  • void push(int x) Push element x to the end of the queue
  • int pop() removes and returns an element from the beginning of the queue
  • int peek() returns the element at the beginning of the queue
  • boolean empty() returns true if the queue is empty; otherwise, returns false

Our implementation idea for this question is to use two stacks, one input stack and one output stack. Data input will be pushed into the input stack. When data is output, it will be popped from the output stack. When the output stack is empty, We need to pop all the data in the input stack and push it into the output stack. Specific code examples are as follows:

class MyQueue {
    
    
  Deque<Integer> inStack = null;
  Deque<Integer> outStack = null;
    public MyQueue() {
    
    
     inStack = new LinkedList<>();
     outStack = new LinkedList<>();
    }
    
    public void push(int x) {
    
    
      inStack.push(x);
    }
    
    public int pop() {
    
    
     if(outStack.isEmpty()){
    
    
         in2out();
     }
     return outStack.pop();
    }
    
    public int peek() {
    
    
    if(outStack.isEmpty()){
    
    
        in2out();
    }
    return outStack.peek();
    }
    
    public boolean empty() {
    
    
    return inStack.isEmpty()&&outStack.isEmpty();
    }
    public void in2out(){
    
    
        while (!inStack.isEmpty()){
    
    
            outStack.push(inStack.pop());
        }
    }
}

Implementing a stack using queues

Let’s look at Likou 225 question:
Please use only two queues to implement a last-in-first-out (LIFO) stack and support all four operations of a normal stack. (push, top, pop and empty).

Implement the MyStack class:

  • void push(int x) Push element x onto the top of the stack.
  • int pop() removes and returns the top element of the stack.
  • int top() returns the top element of the stack.
  • boolean empty() Returns true if the stack is empty; otherwise, returns false.

Our implementation idea for this question is to use two queues. We need to put the newly pushed elements into the front of the queue to facilitate the pop-up order. The order is last in first out, so we use queue 2 to assist queue 1 to operate. We put The elements of the push operation are first put into queue 2, then all the elements in queue 1 are dequeued and put into queue 2, and then queue 1 and queue 2 are exchanged with each other, then the elements in queue 1 are the elements in the stack element.

class MyStack {
    
    
   Queue<Integer> queue1 = null;
   Queue<Integer> queue2 = null;
    public MyStack() {
    
    
  queue1 = new LinkedList<>();
  queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
    
    
     //将元素x压入队列2
     queue2.offer(x);
     //将队列1中的元素压入队列2,并将其弹出
     while (!queue1.isEmpty()){
    
    
         queue2.offer(queue1.poll());
     }
     //交换队列1和队列2
     Queue<Integer> temp = queue1;
     queue1 = queue2;
     queue2 = temp;
    }
    
    public int pop() {
    
    
      //从队列1中弹出元素
      return   queue1.poll();
    }
    
    public int top() {
    
    
      //返回队列1的第一个元素
      return queue1.peek();
    }
    
    public boolean empty() {
    
    
   //判断队列1是否为空
   return queue1.isEmpty();
    }
}

Queue is an important data structure, which has the characteristics of "first in, first out" and is often used to store and access data in order. Understanding the basic concepts, characteristics, and common operations of queues is very important for learning and working in the field of computer science. In practical applications, queues have a wide range of uses, including network transmission, operating systems, task queues, and print queues.

Guess you like

Origin blog.csdn.net/st200112266/article/details/134296427