Objectives of this lecture
Queue Implementation
User Interface:
typedef
char ITEM_TYPE;
typedef
struct node_type { ITEM_TYPE item;
struct node_type *next;
} NODE_TYPE;
typedef
NODE_TYPE *NODE_PTR;
typedef
struct { NODE_PTR front;
NODE_PTR rear;
} Q_TYPE;
typedef
enum {FALSE, TRUE} BOOLEAN;
void
create_queue(Q_TYPE *queue);
void
destroy_queue(Q_TYPE *queue);
BOOLEAN
empty_queue(Q_TYPE *queue);
BOOLEAN
full_queue(Q_TYPE *queue);
void
enqueue(Q_TYPE *queue, ITEM_TYPE new_item);
void
dequeue(Q_TYPE *queue, ITEM_TYPE *front_item);
Implementation Details:
#include
<stdlib.h>
#include
"c:\ics201\queue2.h"
/*
initialize queue by setting both front and rear to NULL */
void
create_queue(Q_TYPE *queue)
{ queue->front=NULL;
queue->rear=NULL;
}
/*
resets queue to empty & returns the nodes being occupied by the elements of
the queue to the system */
void
destroy_queue(Q_TYPE *queue)
{ NODE_PTR temp_ptr;
while ( empty_queue(queue) == FALSE)
{
temp_ptr=queue->front;
queue->front=queue->front->next;
free(temp_ptr);
}
queue->rear = NULL;
}
/*
returns true if front is NULL */
BOOLEAN
empty_queue(Q_TYPE *queue)
{ if (queue->front == NULL)
return TRUE;
else
return FALSE;
}
/*
always returns false */
BOOLEAN
full_queue(Q_TYPE *queue)
{ return FALSE;
}
/*
adds an element to the rear of the queue */
void
enqueue(Q_TYPE *queue, ITEM_TYPE new_item)
{ NODE_PTR new_node;
new_node=(NODE_PTR)
malloc(sizeof(NODE_TYPE));
new_node->item=new_item;
new_node->next=NULL;
if (empty_queue(queue)==TRUE)
queue->front=new_node;
else
/* if the queue is not empty */
queue->rear->next=new_node;
queue->rear=new_node;
}
/*
removes an element from the front of the queue */
void
dequeue(Q_TYPE *queue, ITEM_TYPE *front_item)
{ NODE_PTR temp_ptr;
*front_item=queue->front->item;
temp_ptr=queue->front;
queue->front=queue->front->next;
if (empty_queue(queue)==TRUE)
queue->rear=NULL;
free(temp_ptr);
}