Υλοποίηση σε C

Υλοποίηση με πίνακα

Παράδειγμα 1

struct s_int_queue {
	int values[20];			/* Array of values */
	int head;			/* Head of queue (values[head]) */
	int tail;			/* Tail of queue (values[tail]) */
};

Παράδειγμα 2

struct s_int_queue {
	int *values;			/* Allocated array of values */
	int values_size;		/* Number of values allocated */
	int head;			/* Head of queue (values[head]) */
	int tail;			/* Tail of queue (values[tail]) */
};

Παράδειγμα 3

struct s_int_queue {
	int *values_start;		/* Start of allocated array of values */
	int *values_end;		/* End of allocated array of values */
	int *head;			/* Head of queue  */
	int *tail;			/* Tail of queue  */
};

Υλοποίηση με συνδεδεμένη λίστα

Παράδειγμα

struct s_int_list {
	int val;
	struct s_int_list *next;
};

struct s_int_queue {
	struct s_int_list *head;
	struct s_int_list *tail;
};

/* Add an element to the queue */
void
int_queue_put(struct s_int_queue *q, int v)
{
	struct s_int_list *p;

	p = (struct s_int_list *)malloc(sizeof(struct s_int_list));
	p->next = NULL;
	p->val = v;
	if (q->tail != NULL)
		q->tail->next = p;	/* Add element to queue tail */
	else
		q->head = p;		/* Special case for empty queue */
	q->tail = p;
}

/* Remove and return an element from a non-empty queue */
int
int_queue_get(struct s_int_queue *q)
{
	int v;
	struct s_int_list *tmp;

	assert(q->head != NULL);

	v = q->head->val;
	if (q->head->next == NULL)
		q->tail = NULL;		/* Special case for empty queue */
	tmp = q->head->next;
	free(q->head);
	q->head = tmp;
	return (v);
}