queue是一种先进先出的数据结构。以下由简入繁引入queue。
queue的操作主要有:入队,出队,空满判断等。
1. 数组实现简单队列
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX 10 int arr[MAX]; int head = 0; int tail = 0; int counter = 0; void enqueue(int value) { arr[tail ++] = value; } int dequeue(void) { return arr[head ++]; } bool is_empty(void) { return head == tail; } bool is_full(void) { return tail == MAX; } int main(int argc, char *argv[]) { char ch; while((ch = getchar()) != ' ') { if (! is_full()) { enqueue(ch); } } while(! is_empty()) { putchar(dequeue()); } return 0; }
2. 数组实现循环队列
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX 10 int arr[MAX]; int head = 0; int tail = 0; int counter = 0; void enqueue(int value) { counter ++; arr[tail] = value; tail = (tail + 1) % MAX; } int dequeue(void) { int data; counter --; data = arr[head]; head = (head + 1) % MAX; return data; } bool is_empty(void) { return counter == 0; } bool is_full(void) { return counter == MAX; } int main(int argc, char *argv[]) { char ch; while((ch = getchar()) != ' ') { if (! is_full()) { enqueue(ch); } } while(! is_empty()) { putchar(dequeue()); } return 0; }
3. 链表实现队列
// queue.h #ifndef _QUEUE_H_ #define _QUEUE_H_ #include <stdbool.h> struct node { void *data; struct node *next; }; typedef struct { struct node *head; struct node *tail; } Queue; extern void queue_init(Queue *queue); extern void queue_destroy(Queue *queue, void (*destroy)(void *data)); extern void queue_enqueue(Queue *queue, void *data); extern void *queue_dequeue(Queue *queue); extern bool queue_is_full(Queue *queue); extern bool queue_is_empty(Queue *queue); #endif //_QUEUE_H_
#include <stdlib.h> #include <assert.h> #include "queue.h" void queue_init(Queue *queue) { queue->head = NULL; queue->tail = NULL: } void queue_destroy(Queue *queue, void (*destroy)(void *data)) { while(! queue_is_empty(queue)) { if (destroy) { destroy(queue_dequeue(queue)); } else { queue_dequeue(queue); } } } static struct node * make_node(void *data) { struct node *n; n = malloc(sizeof(struct node)); assert(n); n->data = data; n->next = NULL; return n; } void queue_enqueue(Queue *queue, void *data) { struct node *n; n = make_node(data); if (queue->head == NULL) { queue->head = n; queue->tail = n; } else { queue->tail->next = n; queue->tail = n; } } void *queue_dequeue(Queue *queue) { void *data; struct node *n; n = queue->head; data = n->data; queue->head = n->next; free(n); return data; } bool queue_is_full(Queue *queue) { return false; } bool queue_is_empty(Queue *queue) { return queue->head == NULL; }
参考:
2. 数据结构学习之队列