Java data structures and algorithms Series --- queue

table of Contents

  • 1, the basic concept of the queue
  • 2, Java analog unidirectional queues implemented
  • 3, deque
  • 4, priority queues
  • 5, summary

1, the basic concept of the queue

Queue (Queue) is a special kind of linear form, is special in that it only allows deletion at the front end of the table (Front), while the rear end of insertion, the table (REAR), and stack as a queue table restricted linear modes of operation. Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation. When there is no queue element, called an empty queue. Also known as data elements of the queue queue element. Insert a queue element called into the team in the queue, the queue is deleted from a queue element called a team. Because the queue is inserted only at one end, the other end of the deletion, so only the first element of the queue to enter the first removed from the queue, it is also known as FIFO queue (FIFO-first in first out) linear form. For example, we go to the cinema queue up for tickets, the first to enter the queue sequence is first get a ticket to leave the queue of people, and finally into the queue is the last sequence queuing to buy tickets. For example, in the computer operating system, there are various queues in the quiet work, such as a printer in a print queue waiting to print.

Queue is divided into:

①, unidirectional queue (Queue): the data can only be inserted in one end, the other end of the deleted data.

②, double-ended queue (Deque): each end can insert data and delete data operations.

Here we will introduce a queue - priority queue, the priority queue and the queue is more specialized than the stack data structure, in the priority queue, the data items sorted by keywords, the minimum (or maximum) items in the queue is often foremost, the data item is going to be inserted into an appropriate position to ensure an orderly queue.

2, Java analog unidirectional queues implemented

Before implementation, we look at the following questions:

①, except that the stack, the data in the queue 0 is not always from the beginning of the array index, after removing some of the data queue head front, queue head pointer points to a higher indexing position, as shown below:

②, we then design, when a new data queue, the rear end of the queue pointer will move upwards, i.e. large scale downward direction. Removing items, team front head pointer is moved upward. Well designed and reality seems to the contrary, such as queuing up to buy movie tickets, buying tickets the team's head left, then move forward as a whole team. After You can also delete a number in the queue in the computer, the queue as a whole to move forward, but this is very poor efficiency. We opted for a pointer to move the team head and the tail.

③, so if you move the pointer to the step ②, I believe that the position of the tail pointer quickly moves to the very end of the data, which may be removed over time data, then the team will empty the head, and then came a new data term, since the tail can not move upward, then how to do it? As shown below:

In order to avoid queues dissatisfaction can not insert new data, we can make the tail pointer wraps around to the start position in the array, which is also known as "circular queue."

After understand the principle, Java codes are as follows:

package com.ys.datastructure;
 
public class MyQueue {
    private Object[] queArray;
    //队列总大小
    private int maxSize;
    //前端
    private int front;
    //后端
    private int rear;
    //队列中元素的实际数目
    private int nItems;
     
    public MyQueue(int s){
        maxSize = s;
        queArray = new Object[maxSize];
        front = 0;
        rear = -1;
        nItems = 0;
    }
     
    //队列中新增数据
    public void insert(int value){
        if(isFull()){
            System.out.println("队列已满!!!");
        }else{
            //如果队列尾部指向顶了,那么循环回来,执行队列的第一个元素
            if(rear == maxSize -1){
                rear = -1;
            }
            //队尾指针加1,然后在队尾指针处插入新的数据
            queArray[++rear] = value;
            nItems++;
        }
    }
     
    //移除数据
    public Object remove(){
        Object removeValue = null ;
        if(!isEmpty()){
            removeValue = queArray[front];
            queArray[front] = null;
            front++;
            if(front == maxSize){
                front = 0;
            }
            nItems--;
            return removeValue;
        }
        return removeValue;
    }
     
    //查看对头数据
    public Object peekFront(){
        return queArray[front];
    }
     
     
    //判断队列是否满了
    public boolean isFull(){
        return (nItems == maxSize);
    }
     
    //判断队列是否为空
    public boolean isEmpty(){
        return (nItems ==0);
    }
     
    //返回队列的大小
    public int getSize(){
        return nItems;
    }    
}
复制代码

test:

package com.ys.test;
 
import com.ys.datastructure.MyQueue;
 
public class MyQueueTest {
    public static void main(String[] args) {
        MyQueue queue = new MyQueue(3);
        queue.insert(1);
        queue.insert(2);
        queue.insert(3);//queArray数组数据为[1,2,3]
         
        System.out.println(queue.peekFront()); //1
        queue.remove();//queArray数组数据为[null,2,3]
        System.out.println(queue.peekFront()); //2
         
        queue.insert(4);//queArray数组数据为[4,2,3]
        queue.insert(5);//队列已满,queArray数组数据为[4,2,3]
    }
}
复制代码

3, deque

Deque is both the beginning or end of a queue ends, each end can be inserted into the queue, and removing data items data items, these methods may be referred to:

insertRight()、insertLeft()、removeLeft()、removeRight()

If the call is strictly prohibited insertLeft () and removeLeft () (or disable the right operation), then the function deque to speak in front of the stack and function the same. If the call is strictly prohibited insertLeft () and removeRight (or opposite another method), then the function deque queue on the way and the same.

4, priority queues

Priority queue (priority queue) is more specific than the stack and queue data structure, in the priority queue, the data items sorted by keywords, the minimum (or maximum) at the front of the queue items often, and data item is going to be inserted into an appropriate position to ensure an orderly queue.

Priority queue is 0 or a collection of elements, each element has a priority, the priority queue has the operation executed:

** (1) ** Find ** (2) ** ** insert a new element (3) Delete **

Under normal circumstances, the search operation to search for the largest element of priority, delete operation to delete the element. Filed for the same elements, FIFO may be performed in any order or priority treatment. Here we implemented priority queue array, this method is relatively slow insertion, but it is relatively simple for a small amount of data and is not the case with particular emphasis on the speed of insertion. Later we will explain heap, stack data structure to achieve the priority queue, you can insert data quite fast. Array implemented priority queue, declared as an array of type int, which is an array of key elements are arranged in descending order when inserted, it is smaller the higher the priority elements.

package com.ys.datastructure;
 
public class PriorityQue {
    private int maxSize;
    private int[] priQueArray;
    private int nItems;
     
    public PriorityQue(int s){
        maxSize = s;
        priQueArray = new int[maxSize];
        nItems = 0;
    }
     
    //插入数据
    public void insert(int value){
        int j;
        if(nItems == 0){
            priQueArray[nItems++] = value;
        }else{
            j = nItems -1;
            //选择的排序方法是插入排序,按照从大到小的顺序排列,越小的越在队列的顶端
            while(j >=0 && value > priQueArray[j]){
                priQueArray[j+1] = priQueArray[j];
                j--;
            }
            priQueArray[j+1] = value;
            nItems++;
        }
    }
     
    //移除数据,由于是按照大小排序的,所以移除数据我们指针向下移动
    //被移除的地方由于是int类型的,不能设置为null,这里的做法是设置为 -1
    public int remove(){
        int k = nItems -1;
        int value = priQueArray[k];
        priQueArray[k] = -1;//-1表示这个位置的数据被移除了
        nItems--;
        return value;
    }
     
    //查看优先级最高的元素
    public int peekMin(){
        return priQueArray[nItems-1];
    }
     
    //判断是否为空
    public boolean isEmpty(){
        return (nItems == 0);
    }
     
    //判断是否满了
    public boolean isFull(){
        return (nItems == maxSize);
    }
}
复制代码

insert () method to check for any data item in the queue, if not, directly inserted into the labeled cell 0, otherwise, start comparing the top of the array, to find insertion than the insertion smaller value of the position, and the nItems plus 1.

remove () method of direct access to the top element.

Priority queue insertion operation requires O (N) time, and delete operations will need to O (1) time, the back will explain how to improve the insertion time by the stack.

5, summary

In this article we introduced three forms of queues, queues are one-way, two-way queue, and priority queues. In fact, we listen to the name can also hear the difference between them, follow the principle of one-way FIFO queue, and can only be inserted one end, the other end can only be deleted. Deque the ends can be inserted into and removed if a certain period of bi-directional queue limit method, and can achieve the same function unidirectional queues. Finally, priority queues, it is a priority in ordering the insertion element when, in the practical application of individual queues and priority queue to use more. Explained heap behind this data structure, we will use the heap to implement a priority queue, improve time priority queue insert elements.

By speaking in front of stacks and queues Benpian say these two data structures, we summarize a little:

①, stacks, queues (queue-way), the priority queue data structure is typically used to simplify some operations program, rather than primarily as a storage data.

②, in these data structures, only one data item can be accessed.

③, press-fitting the stack allowing the stack data (insert), the pop-up (removed) in the data stack, but can only access the last data item is inserted, i.e. the top element.

④, queue (queue-way) can only be inserted in the tail data, delete data head, and the head can only access data. And circular queue queue may also be implemented, which is based on an array, the array may be wound from the end of an array subscript of the array back to the starting position.

⑤, priority queues are ordered insertion of data and can only access the current element priority maximum (or minimum) elements.

⑥, these data structures can be implemented by arrays, but can be achieved by other mechanisms (behind talk of a linked list, stack data structure, etc.).

Guess you like

Origin juejin.im/post/5def9415f265da33b5073021
Recommended