CS221 - Data Structures & Algorithms: Queues
CS221 - Data Structures & Algorithms: Queues
Algorithms
Queues
Queue
• An Ordered list in which insertions occur at
one end (rear) and deletions occur at the
other end (front).
• Its operation preserves the entry order of the
elements, a queue is a first-in, first-out (FIFO)
list.
Queue
• In a FIFO data structure, the first element
added to the queue will be the first one to be
removed.
• Whenever an element is added, all elements
that were added before have to be removed
before the new element can be invoked.
Queue Operations
• Enqueue
– Inserts an element at the end of the list, called the
rear.
• Dequeue
– Deletes and returns the element at the start of
list, called the front.
Queue Implementation
• struct Node
• {
– ElementType Element;
– struct Node *Next;
• }
Queue Implementation
• typedef struct Node* PointerToNode;
• typedef PointerToNode Front; //F
• typedef PointerToNode Rear; //R
Queue Implementation
• Enqueue
Queue Implementation
• Enqueue
Node* MyNewNode = CreateNewNode(sizeof(Node))
MyNewNodeElement = A
MyNewNodeNext = RNext
Queue Implementation
• Enqueue
RNext = MyNewNode
Queue Implementation
• Enqueue
R = MyNewNode
Queue Implementation
• Enqueue
Node* MyNewNode = CreateNewNode(sizeof(Node))
MyNewNodeElement = B
MyNewNodeNext = RNext
Queue Implementation
• Enqueue
RNext = MyNewNode
Queue Implementation
• Enqueue
R = MyNewNode
Queue Implementation
• EnqueueAlgo
• {
– Node* MyNewNode = CreateNewNode(sizeof(Node))
– MyNewNodeElement = X
– MyNewNodeNext = RearNext
– RearNext = MyNewNode
– Rear = MyNewNode
• }
Queue Implementation
• void Enqueue(ElementType x, Rear R)
• {
– Node* MyNewNode = malloc(sizeof(struct
Node));
– MyNewNodeElement = x;
– MyNewNodeNext = RNext;
– RNext = MyNewNode;
– R = MyNewNode;
• }
Queue Implementation
• Dequeue Algo
• {
– Node* Temp = Front Next
– Front Next = Temp Next
– Return Temp
• }
Queue Implementation
• struct Node* Dequeue(Front F)
• {
– Node* TempNode;
– TempNode = F Next;
– F Next = TempNode Next;
– return TempNode;
• }
Array Implementation of Queue
• We maintain an array Queue[] & the positions
Front and Rear.
• We keep the track of the number of elements in
the queue with Size.
• To enqueue an element x in the queue, increment
the Size and the rear, then set Queue[Rear] = x.
• To dequeue an element , set the return value to
Queue[Front], decrement the Size and then
increment the Front.
Array Implementation of Queue
• struct QueueRecord
• {
– int Capacity;
– int Front = 0;
– int Rear = -1;
– int Size;
– ElementType *Array;
• }
Array Implementation of Queue
• void Enqueue(ElementType x, Queue Q)
• {
– QSize++;
– QRear++;
– QArray[QRear] = x
• }
Array Implementation of Queue
• ElementType Dequeue(Queue Q)
• {
– ElementType temp = QArray[QFront];
– QSize--;
– QFront++;
– return temp;
• }