2

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.”

MJD
  • 65,394
  • 39
  • 298
  • 580
Mary Star
  • 13,956

2 Answers2

3

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.

  • I got stuck right now..You said that "When the two pointers (indices) head[Q], end[Q] are equal that means the queue is empty ". But when head[Q]=end[Q]=1 why does this mean that they both point to the first element of the array ?? The pointer end[Q] shows to the first empty position, or not? Should it maybe be head[Q]=end[Q]-1 when there is one element in the queue?
  • – Mary Star Aug 25 '14 at 16:50
  • 1
    Because head[Q]=1 and end[Q]=1 at the same time. Yes, end[Q] shows the first empty position. When there's one element in the queue, say at position $i,$ then head[Q]=i and end[Q]=i + 1 $\text{mod} ; n$ where $n=\text{length}(Q).$ So head[Q]=end[Q] + 1 ($\text{mod} ; n$). – Ehsan M. Kermani Aug 25 '14 at 16:57
  • So, head[Q]=end[Q]=1 stands when there are no elements in the queue?? – Mary Star Aug 25 '14 at 17:02
  • 1
    right! that's only because head[Q]=end[Q] and note that you should start from somewhere, say at Q[1]. – Ehsan M. Kermani Aug 25 '14 at 17:11
  • Great!!! Thanks a lot!!! – Mary Star Aug 27 '14 at 00:30