Understanding queue arithmetic in data structures -


when element inserted in queue, rear = rear + 1. when element deleted queue, front = front + 1 when queues implemented using arrays.

now, initially, both front = rear = -1 indicating queue empty. when first element added, front = rear = 0 (assuming array 0 n-1).

now, if assume condition front = 0 , rear = n-1 implying queue full. when few elements removed front pointer changes. let front = 5 , rear = 10. hence, array locations 0 4 free.

when wish add element now, add @ location 0 , front points it. locations 1, 2, 3 , 4 free.

but, when next time try insert element, compiler throw error saying queue full. since front = 0 , rear = n-1. how insert @ remaining locations , understand queuing arithmetic better?

i understand how front = rear + 1 acts condition checking if queue full?

you want think circularly here in terms of relative, circular ranges instead of absolute, linear ones. don't want hung on absolute indices/addresses of front , rear. they're relative each other, , can use modulo arithmetic start getting beginning of array pac-man when goes off side of screen. can useful when you're drawing these things out literally draw array circle on whiteboard.

when wish add element now, add @ location 0 , front points it. locations 1, 2, 3 , 4 free.

i think here got backwards bit. according logic, insertions advance rear, not front. in such case, rear @ 0, , front still @ 5. if push again, rear=1 , you'd overwrite first index, , front still 5.

if n=3 , front=2 , rear=2, have 1 element in queue after pushing , popping lot. when push (enqueue), set: rear=(rear+1)%n making front=2, rear=0 giving 2 elements. if push again, front=2, rear=1 giving 3 elements, , queue full.

visually:

     r   [..x]      f     r   [x.x]      f      r   [xxx]      f 

... , we're full. queue full if next circular index rear front. in case front=2, rear=1, can see (rear+1)%n == front, it's full.

if popped (dequeued) @ point @ point, set front=(front+1)%n , this:

    r   [xx.]    f 

i understand how front = rear + 1 acts condition checking if queue full?

this doesn't suffice when use kind of circular indexing. need slight augmentation: queue full when front == (rear+1)%n. need modulo arithmetic handle "wrap around other side" cases.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -