C语言队列基本操作
#define MaxSize 100
#include <stdio.h>
#include<stdbool.h>
typedef struct {int data[MaxSize];int front;//隊頭元素int rear;//隊尾元素指向隊尾元素下一個位置
}SqQueue;//順序存儲隊列
void InitQueue(SqQueue Q) {Q.front = Q.rear = 0;//初始化空隊列
}
bool isEmpty(SqQueue Q) {if (Q.front = Q.rear = 0)return true;elsereturn false;
}//判空
bool INQueue(SqQueue Q, int x) {if ((Q.rear + 1) % MaxSize == Q.front){return false;//隊列已滿
}else {Q.data[Q.rear] = x;Q.rear = (Q.rear + 1) % MaxSize;}return true;
}//入隊
bool OUTQueue(SqQueue Q, int x) {if (Q.rear = Q.front = 0) {return false;//隊列為空}else {Q.data[Q.front] = x;Q.front = (Q.front + 1) % MaxSize;}return true;
}//出隊
/*為解決隊列假溢出使用循環(huán)隊列
隊首指針進1 Q.front=(Q.front+1)%MaxSize
隊尾指針進1 Q.rear=(Q.rear+1)%MaxSize
隊列長度 (Q.rear+MaxSize-Q.front)%MaxSize
*/
typedef struct LNode {int data;struct LNode* next;
}LNode;//定義結(jié)點
typedef struct LinkQueue {LNode* front;//隊頭指針LNode* rear;//隊尾指針
}LinkQueue;//定義鏈式存儲隊列
void InitQueue(LinkQueue Q) {Q.front = Q.rear = (LNode*)malloc(sizeof(LNode));Q.front->next = Q.rear->next = NULL;//帶頭結(jié)點
}//初始化
bool isEmpty(LinkQueue Q) {if (Q.front != Q.rear)return false;elsereturn true;
}//判空
void INQueue(LinkQueue Q,int x) {LNode* s = (LNode*)malloc(sizeof(LNode));s->data = x;Q.rear->next = s;Q.rear = s;
}//入隊
bool OUTQueue(LinkQueue Q, int x) {if (Q.front == Q.rear)return false;else {LNode* p = Q.front->next;p->data = x;Q.front->next = p->next;if (p->next == Q.rear) {Q.front == Q.rear;}free(p);}return true;
}//入隊
總結(jié)
- 上一篇: vscode中文乱码
- 下一篇: 华硕重装系统键盘灯失效 =重装ATK驱