/*
* 单链队列的实现
*/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
/*
* 自定义BOOL类型
*/
typedef int BOOL;
#define TRUE 1;
#define FALSE 0;
typedef int datatype;
/*
* 结点
*/
typedef struct Node {
datatype data;
struct Node *next;
}Node;
typedef struct {
Node *front;
Node *rear;
}Queue;
/*
* 单链队列的初始化
*/
void initQueue(Queue *queue) {
//为了操作方便,设置一个头结点,并将头指针指向头结点
queue->front = queue->rear = (Node*)malloc(sizeof(Node));
if(queue->front == NULL) {
printf("分配失败!");
exit(1);
}
queue->front->next = NULL;
queue->rear->next = NULL;
}
/*
* 单链队列插入新的结点(只能在队列的尾部插入结点)
*/
BOOL enQueue(Queue *queue, datatype elem) {
Node *p = (Node*) malloc(sizeof(Node));
if(p == NULL) {
return FALSE;
}
p->data = elem;
p->next = NULL;
queue->rear->next = p;
queue->rear = p;
return TRUE;
}
/*
* 单链队列删除结点
*/
BOOL deQueue(Queue *queue, datatype *elem) {
//判断队列是否为空
if(queue->front == queue->rear) {
printf("队列是空的!");
return FALSE;
}
Node *p = queue->front->next;
*elem = p->data;
queue->front->next = p->next;
//队列中只有一个p结点,该结点被删除后队列为空
if(queue->rear == p) {
queue->rear = queue->front;
}
free(p);
return TRUE;
}
/*
* 销毁单链队列
*/
void clear(Queue *queue) {
while(queue->front != NULL) {
queue->rear = queue->front->next;
free(queue->front);
queue->front = queue->rear;
}
}
/*
* 打印出队列中的元素
*/
void printQueue(Queue *queue) {
Node *p = queue->front->next;
while(p != NULL) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(void) {
Queue q;
initQueue(&q);
for(int i = 0; i < 10; i++) {
enQueue(&q, i);
}
printQueue(&q);
int tmp;
deQueue(&q, &tmp);
printQueue(&q);
}