队列的顺序存储
#include
#define MaxSize 10
using namespace std;
//顺序队列
typedef struct {
int data[MaxSize];
int front, rear;
}SqQueue;
//初始化队列
bool InitSqQueue(SqQueue &Q){
Q.front = Q.rear = 0;
}
//入队操作
bool EnQueue(SqQueue& Q,int e) {
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MaxSize;
}
//出队操作
bool DeQueue(SqQueue& Q, int& e) {
if (Q.rear == Q.front)
return false;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
}
int main() {
SqQueue Q;
InitSqQueue(Q);
int a = (Q.rear - Q.front + MaxSize) % MaxSize; **//队中元素个数**
return 0;
}
队列的链式存储
#include
using namespace std;
//带头结点的链队
typedef struct LinkNode{
int data;
struct LinkNode* next;
}LinkNode;
typedef struct SqQueue {
struct LinkNode* front, * rear;
}SqQueue;
//初始化带头结点的链队列
bool InitSqQueue(SqQueue& Q) {
Q.front = Q.rear = new LinkNode;
Q.front->next = NULL;
}
//初始化不带头结点的链队列
//bool InitSqQueue(SqQueue& Q) {
// Q.front = Q.rear = NULL;
//}
bool IsEmpty(SqQueue Q) {
return(Q.front == Q.rear);// 方法一
return(Q.front->next == NULL);//方法二
}
//带头结点的链队列入队操作
void EnQueue(SqQueue& Q,int e) {
LinkNode* s = new LinkNode;
s->data = e;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
}
//不带头结点的链队列入队操作
void EnQueue(SqQueue& Q, int e) {
LinkNode* s = new LinkNode;
s->data = e;
s->next = NULL;
if (Q.rear->next == NULL) {
Q.rear = Q.front = s;
}
else {
Q.rear->next = s;
Q.rear = s;
}
}
//带头结点的链队列出队
bool DeQueue(SqQueue& Q, int& e) {
if (Q.front == Q.rear)
return false;
LinkNode* s = Q.front->next;
e = s->data;
Q.front->next = s->next;
if (s == Q.rear) {
Q.front = Q.rear;
}
delete(s);
return true;
}
//不带头结点的链队列出队
//bool DeQueue(SqQueue& Q,int &x) {
// if (Q.front == Q.rear)
// return false;
// LinkNode* s = Q.front;
// x = s->data;
// Q.front = s->next;
// if (Q.rear = s) {
// Q.front = Q.rear = NULL;
// }
// delete(s);
// return true;
//}
int main() {
SqQueue Q;
InitSqQueue(Q);
return 0;
}