|
|
1.1 root 1: /*
2: * File: queue.c
3: * Author: Robert I. Pitts <[email protected]>
4: * Last Modified: March 9, 2000
5: * Topic: Queue - Array Implementation
6: * ----------------------------------------------------------------
7: */
8:
9: #include <stdio.h>
10: #include <stdlib.h>
11: #include "queue.h"
12:
13: /*
14: * Constants
15: * ---------
16: * MAX_QUEUE_SIZE = Largest number of items queue can hold.
17: */
18:
19: #define MAX_QUEUE_SIZE 100
20:
21: /*
22: * struct queueCDT gives the implementation of a queue.
23: * It holds the information that we need for each queue.
24: */
25: typedef struct queueCDT {
26: queueElementT contents[MAX_QUEUE_SIZE];
27: int front;
28: int count;
29: } queueCDT;
30:
31: queueADT QueueCreate(void)
32: {
33: queueADT queue;
34:
35: queue = (queueADT)malloc(sizeof(queueCDT));
36:
37: if (queue == NULL) {
38: fprintf(stderr, "Insufficient Memory for new Queue.\n");
39: exit(ERROR_MEMORY); /* Exit program, returning error code. */
40: }
41:
42: queue->front = 0;
43: queue->count = 0;
44:
45: return queue;
46: }
47:
48: void QueueDestroy(queueADT queue)
49: {
50: free(queue);
51: }
52:
53: void QueueEnter(queueADT queue, queueElementT element)
54: {
55: int newElementIndex;
56:
57: if (queue->count >= MAX_QUEUE_SIZE) {
58: // fprintf(stderr, "QueueEnter on Full Queue.\n");
59: // exit(ERROR_QUEUE); /* Exit program, returning error code. */
60: return;
61: }
62:
63: /*
64: * Calculate index at which to put
65: * next element.
66: */
67: newElementIndex = (queue->front + queue->count)
68: % MAX_QUEUE_SIZE;
69: queue->contents[newElementIndex] = element;
70: //printf("element %d, pointer to %d, [%s]\n",newElementIndex,element,element);
71:
72: queue->count++;
73: }
74:
75: int QueuePeek(queueADT queue)
76: {
77: return queue->count;
78: }
79:
80: queueElementT QueueDelete(queueADT queue)
81: {
82: queueElementT oldElement;
83:
84: if (queue->count <= 0) {
85: //fprintf(stderr, "QueueDelete on Empty Queue.\n");
86: //exit(ERROR_QUEUE); /* Exit program, returning error code. */
87: return NULL;
88: }
89:
90: /* Save the element so we can return it. */
91: oldElement = queue->contents[queue->front];
92:
93: /*
94: * Advance the index of the front,
95: * making sure it wraps around the
96: * array properly.
97: */
98: queue->front++;
99: queue->front %= MAX_QUEUE_SIZE;
100:
101: //printf("dequing @%d [%s]\n",oldElement,oldElement);
102:
103: queue->count--;
104:
105: return oldElement;
106: }
107:
108: int QueueIsEmpty(queueADT queue)
109: {
110: return queue->count <= 0;
111: }
112:
113: int QueueIsFull(queueADT queue)
114: {
115: return queue->count >= MAX_QUEUE_SIZE;
116: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.