- 一个结构体来实现链表节点。
- 一个结构体来存放队列的rear指针和front指针。
#include <stdio.h>
typedef int ElemType;
typedef struct QueueNode{
ElemType data;
struct QueueNode *next;
}QueueNode;
typedef struct QueueP{
QueueNode *front,*rear;
};
int main() {
return 0;
}
void queue_init(QueueP &queueP) {
queueP.front = queueP.rear = (QueueNode *) malloc(sizeof(QueueNode));
queueP.rear->next = NULL;
};
- 尾插法入队(头插法和尾插法都可以实现入队和出队),链表无需考虑队列容量问题
void queue_en(QueueP &queueP, ElemType elem) {
QueueNode *queueNodeNew = (QueueNode *) malloc(sizeof(QueueNode));
queueNodeNew->data = elem;
queueNodeNew->next = queueP.rear->next;
queueP.rear->next = queueNodeNew;
queueP.rear = queueNodeNew;
}
- 头部出队,需要考虑两个边际问题,队列只有一个元素时,队列为空时。
bool queue_de(QueueP &queueP, ElemType &elem) {
if (queueP.front == queueP.rear) {
return false;
}
QueueNode *queueNode = queueP.front->next;
queueP.front->next = queueNode->next;
elem = queueNode->data;
if (queueNode == queueP.rear) {
queueP.rear = queueP.front;
}
free(queueNode);
return true;
}
全部代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct QueueNode {
ElemType data;
struct QueueNode *next;
} QueueNode;
typedef struct QueueP {
QueueNode *front, *rear;
};
void queue_init(QueueP &queueP) {
queueP.front = queueP.rear = (QueueNode *) malloc(sizeof(QueueNode));
queueP.rear->next = NULL;
};
void queue_en(QueueP &queueP, ElemType elem) {
QueueNode *queueNodeNew = (QueueNode *) malloc(sizeof(QueueNode));
queueNodeNew->data = elem;
queueNodeNew->next = queueP.rear->next;
queueP.rear->next = queueNodeNew;
queueP.rear = queueNodeNew;
}
bool queue_de(QueueP &queueP, ElemType &elem) {
if (queueP.front == queueP.rear) {
return false;
}
QueueNode *queueNode = queueP.front->next;
queueP.front->next = queueNode->next;
elem = queueNode->data;
if (queueNode == queueP.rear) {
queueP.rear = queueP.front;
}
free(queueNode);
return true;
}
int main() {
QueueP queueP;
ElemType elem;
queue_init(queueP);
queue_en(queueP, 1);
queue_en(queueP, 2);
queue_de(queueP, elem);
queue_de(queueP, elem);
return 0;
}