Objectives of this lecture
Review
Dynamic Implementation of Stack.
/* file name: queue.h */
#include
“common.h”
typedef
…. QueueEntry; //datatype for the items
in the queue
typedef
struct queuenode { QueueEntry info;
struct queuenode *next;
} QueueNode;
typedef
struct queue { QueueNode *front;
QueueNode *rear;
}
Queue;
void CreateQueue(Queue *q);
void ClearQueue(Queue *q);
void Append(QueueEntry newitem, Queue *q);
void Serve(QueueEntry *frontitem, Queue *q);
Boolean
QueueEmpty(Queue *q);
Boolean
QueueFull(Queue *q);
//file
name: queue.c
#include
“queue.h”
QueueNode
*MakeNode(QueueEntry item);
/*
CreateQueue: create the queue.
Pre: None.
Post:
The queue q has been initialized to be empty.
*/
void
CreateQueue(Queue *q)
{ q->front = q->rear = NULL;
}
/*
AppendNode: append an entry to the
queue.
Pre: newitem is a valid queue entry
Post:
new node is created, the new item has been placed in the
new node and rear points to the new node. If this is the first
node, front
also points to it
Uses:
QueueEmpty, MakeNode, Error. */
void Append(QueueEntry newitem, Queue *q)
{
QueueNode *p = MakeNode(newitem);
if (p != NULL)
Error("Attempt to append a
nonexistent node to the queue.");
else if (QueueEmpty(q)) /* Set both front
and rear to p. */
q->front = q->rear = p;
else {
q->rear->next = p;
q->rear = p;
}
}
/*
ServeNode: remove the first entry in
the queue.
Pre: The linked queue q has been created and is
not empty.
Post:
The first node in the queue has been removed and parameter
p points to this node.
Uses:
QueueEmpty, Error.
*/
void Serve(QueueEntry *frontitem, Queue *q)
{ QueueNode *p;
if (QueueEmpty(q))
Error("Attempt to delete a node
from an empty queue.");
else {
p = q->front;
q->front =
q->front->next;
if (QueueEmpty(q)) /* Is the queue now empty? */
q->rear = NULL;
*frontitem =p->info;
free(p);
}
}
/*
MakeNode: make a new node and insert item.
Pre: None.
Post:
Create a new node and insert item in it.
*/
QueueNode
*MakeNode(QueueEntry item)
{ QueueNode *nodepointer;
nodepointer = (QueueNode *)
malloc(sizeof(QueueNode));
if (nodepointer == NULL)
Error("Exhausted memory.");
else
{
nodepointer->info = item;
nodepointer->next = NULL;
}
return nodepointer;
}
Exercises:
ClearQueue,
QueueEmpty, QueueFull