Question about queues

84 Views Asked by At

A queue is implemented with a sequence $Q[1\ldots n]$ and two indices $\def\head{\operatorname{head}}\head[Q]$ and $\def\end{\operatorname{end}}\end[Q]$ such that the elements of the queue are the following:

$$Q[\head[Q]], Q[\head[Q]+1], \ldots , Q[\end[Q]-1]$$

Initial $\head[Q]=\end[Q]=1$

When $\head[Q]=\end[Q]+1$ the queue is complete.

  1. Does ”Initial $\head[Q]=\end[Q]=1$” stand when there is one element in the queue?

  2. Could you explain me what the following means?

”When $\head[Q]=\end[Q]+1$ the queue is complete.”

2

There are 2 best solutions below

3
On BEST ANSWER

When $head=end$ we consider the queue empty.

If there is 1 element in the queue, the queue looks like: $$-\ \ - \ - \underset{\stackrel\uparrow{head}}o \underset{\stackrel\uparrow{end}}- \ \ -$$ That means that: $$head+1 \equiv end\pmod{n}$$

At some point in time the queue might look like: $$o \underset{\stackrel\uparrow{end}}- - \underset{\stackrel\uparrow{head}}o o \ \ o$$

If we add one more element at the end, we get: $$o\ \ o \underset{\stackrel\uparrow{end}}- \underset{\stackrel\uparrow{head}}o o\ \ o$$

At this point we cannot add any more elements, because if $head=end$, that means we consider this an empty queue. In other words, the queue is full or complete when: $$end+1 \equiv head \pmod{n}$$

5
On

1) When the two pointers (indices) head[Q], end[Q] are equal that means the queue is empty (which is what we want initially) and when head[Q]=end[Q]=1 that means they both point to the first element of our array to start the queue.

2) When head[Q] -1 = end[Q], the queue is full and there is no other place to put an element there. head[Q] points to the first element of the queue and end[Q] points to the first empty place that a new element can go there. Note that, the pointer end[Q] is cyclic, i.e. after Q[n] was used, it starts from the first position Q[1] of the array.