A queue is an ADT which allows data values to be accessed only one at a time and only the first inserted. The rule imposed on a queue is: First In First.

Similar presentations

Presentation on theme: "A queue is an ADT which allows data values to be accessed only one at a time and only the first inserted. The rule imposed on a queue is: First In First."— Presentation transcript:

1

2
A queue is an ADT which allows data values to be accessed only one at a time and only the first inserted. The rule imposed on a queue is: First In First Out queue requires methods: insert( ), remove( ), peek( ), isEmpty( ), sometimes isFull( )(depending on the implementation) and size() which is optional. queues are often used as aids in more complex data structures and like stacks are considered a programmer’s tool.

3
When is a queue empty? If size() method is used, when number of items is 0. If size() method is not used, maybe when rear = front - 1 To follow the rule: FIFO we must keep track of the location of the first item inserted and the last item inserted by private data fields front and rear. (insertions are made at the rear - deletions are made from the front ) In an array implementation of a queue, to what should we initialize front? zero In an array implementation of a queue, to what should we initialize rear? To insert into a queue we increment rear. To remove from a queue what should we do to front? Increment front

5
Front =2 Rear = 6 Rear == maxsize - 1 BUT the queue is NOT full - we can wrap around and fit in two more items. Q.insert(17) rear ==0 front ==2 17 Q.insert(18) rear ==1 front ==2 18 The queue is now full and rear == front -1 !?!?That is the condition when the queue is empty!?!?

6
After q.remove() is executed 6 times 18 Rear == 1 and front == 1 Q.remove() now produces front ==2rear == 1 The queue is empty and rear == front - 1 !?!? To avoid this problem we have two choices: use the size() method to keep track of the number of elements in the queue OR use an array that is 1 space larger than needed. (see p ) (the same condition that existed when the queue was full)