数据结构(C&C++)
队列(牺牲一个节点判断队满的循环队列)
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef struct {
int data[MaxSize];
int front, rear;
}SqQueue;
void IniQueue(SqQueue& Q) {
Q.front = Q.rear = 0;
}
bool IsQEmpty(SqQueue Q) {
if (Q.front == Q.rear)
return true;
else
{
return false;
}
}
bool EnQueue(SqQueue& Q, int x) {
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue& Q,int &x) {
if (Q.front == Q.rear)
return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
typedef struct {
int data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
void IniLinkQueue(LinkQueue& Q) {
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
bool IsLinkQEmpty(LinkQueue Q) {
if (Q.front == Q.rear)
return true;
else
{
return false;
}
}
void EnLinkQ(LinkQueue& Q, int x) {
LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = x;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
bool DeLinkQ(LinkQueue& Q, int& x) {
if (Q.front = Q.rear)
return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (Q.rear == p) //若队列中仅有一个元素,则删除后队列变空,需要特殊处理
Q.rear = Q.front;
free(p);
return true;
}
SqQueue Q1, Q2, Q; //Q表示渡轮,Q1,Q2表示客车队列,货车队列
void Manager() {
int i = 0, j = 0; //j表示一趟渡轮上的车辆数
int x;
while (j < 10) {
if (!IsQEmpty(Q1) && i < 4) {
DeQueue(Q1, x);
EnQueue(Q, x);
i++;
j++;
}
else if (i == 4 && !IsQEmpty(Q2)) {
DeQueue(Q2, x);
EnQueue(Q, x);
j++;
i = 0;
}
else
{
while (j<10&&i<4&&!IsQEmpty(Q2))
{
DeQueue(Q2, x);
EnQueue(Q, x);
i++;
j++;
}
i = 0;
}
if (IsQEmpty(Q1) && IsQEmpty(Q2))
j = 11;
}
}