G
G
gleendo2016-12-06 08:48:16
Java
gleendo, 2016-12-06 08:48:16

How to understand the cyclic queue algorithm?

More or less figured out the fixed queue, but now I can’t understand the condition check in the cyclic queue.
There is such a piece of code with the implementation of the put () method.

public class CircularQueue {
    private char[] q;
    private int putLoc, getLoc;

    public CircularQueue(int size) {
        q = new char[size + 1];

        putLoc = getLoc = 0;
    }

    public void put(char ch) {
        if (putLoc + 1 == getLoc | ((putLoc == q.length - 1) & (getLoc == 0))) {
            System.out.println("Очередь заполнена");
            
            return;
        }
        
        if (putLoc == q.length) {
            putLoc = 0;
        }
        
        q[++putLoc] = ch;
    }
}

Please explain how to understand what is being checked in the put() method.
How to understand this line if (putLoc + 1 == getLoc | ((putLoc == q.length - 1) & (getLoc == 0)))?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2016-12-06
@evgeniy8705

Let it be your turn:
--++++---
(Pluses where occupied)
putloc - index of the place in the array where the data is put (the last place where the plus was put, the rightmost one), getloc - where the pluses are taken from (the leftmost plus)
--[++++]---
Since the queue is cyclic, the right border of pluses can catch up with the left
++][+++++++
this is checked (putloc+1 = getloc)
Well, if the border is exactly at the end array, you need a second test condition
[+++++++++]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question