隊列(Queue)是一種類似棧的數據結構, 棧是"後進先出", 而隊列是"先進先出"; 隊列通常模擬進出一致的數據處理場景, 例如消息推送處理, 商城中的購物處理等.
循環隊列預備知識:
- 循環隊列無法區分隊空或隊滿, 解決辦法: rear+1 == front mod 數組長度
- 隊空條件: front==rear (初始值: front = rear)
- 判斷隊滿: (rear+1)%MAXQSIZE == front
- 隊列長度: (rear - front + MAXQSIZE) % MAXSIZE
- 最大存儲 MAX_SIZE - 1 個元素
鏈式隊列預備知識
- 一般使用帶頭鏈表實現, 初始化時front和rear指針指向此元素
- 判斷隊列是否爲空: front==rear
- 第一個隊列元素: front.next
循環隊列(數組)
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
#define MAX_SIZE 5
typedef int ElemType;
typedef int status;
typedef struct {
ElemType *base;
int front;
int rear;
} SqQueue;
status InitQueue(SqQueue &Q) {
if (!Q.base) exit(OVERFLOW);
Q.base = (ElemType *) malloc(sizeof(ElemType) * MAX_SIZE);
Q.rear = Q.front = 0;
return OK;
}
status EnQueue(SqQueue &Q, ElemType e) {
if (!Q.base) return ERROR;
if ((Q.rear + 1) % MAX_SIZE == Q.front)exit(OVERFLOW);
Q.base[Q.rear] = e;
Q.rear = (Q.rear+1) % MAX_SIZE;
return OK;
}
status DeQueue(SqQueue &Q, ElemType &e) {
if (!Q.base) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front+1) % MAX_SIZE;
return OK;
}
status isEmpty(SqQueue Q) {
if(Q.rear == Q.front) return TRUE;
return FALSE;
}
int main() {
SqQueue Q;
InitQueue(Q);
EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
EnQueue(Q,4);
ElemType e;
DeQueue(Q,e);
EnQueue(Q,5);
while(!isEmpty(Q)){
DeQueue(Q,e);
printf("%d\n",e);
}
return 0;
}
鏈式隊列
typedef struct QNode {
ElemType data;
struct QNode *next;
} QNode, *QNodePtr;
typedef struct {
QNodePtr front;
QNodePtr rear;
} *LinkQueue;
void InitLinkQueue(LinkQueue &Q) {
Q = (LinkQueue)malloc(sizeof(LinkQueue));
QNode *node = new QNode;//頭結點
node->data = -1;
node->next = NULL;
Q->front = node;
Q->rear = node;
}
status EnLinkQueue(LinkQueue &Q, ElemType e) {
if (!Q) exit(OVERFLOW);
QNode *p = new QNode;
p->data = e;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return OK;
}
status DeLinkQueue(LinkQueue &Q, ElemType &e) {
if (!Q)return ERROR;
if (Q->rear == Q->front) return ERROR;
QNodePtr de_node = Q->front->next;
e = de_node->data;
if (de_node == Q->rear) {
Q->rear = Q->front;
} else {
Q->front->next = de_node->next;
}
free(de_node);
return OK;
}
status DestroyLinkQueue(LinkQueue &Q){
if(!Q)return ERROR;
if(Q->front==Q->rear)return OK;//無內容
QNodePtr p;
while(Q->front != Q->rear){
p = Q->front->next;
Q->front->next = p->next;
free(p);
}
Q->rear = Q->front;
return OK;
}
status isEmpty(LinkQueue Q) {
if (Q->front == Q->rear) return TRUE;
return FALSE;
}
int length(LinkQueue Q){
QNodePtr p = Q->front;
int n=0;
while(p != Q->rear){
n++;
p = p->next;
}
return n;
}
int main(){
LinkQueue Q;
InitLinkQueue(Q);
EnLinkQueue(Q,1);
EnLinkQueue(Q,2);
EnLinkQueue(Q,3);
EnLinkQueue(Q,4);
printf("len: %d\n",length(Q));
ElemType e;
while(!isEmpty(Q)){
DeLinkQueue(Q, e);
printf("%d\n",e);
}
return 0;
}