题目要求:
我的代码实现:
(1)顺序队列实现:
#include<stdio.h>
#include<string.h>
//顺序队列基本数据类型定义:
#define ElemType char
#define MaxSize 50
typedef struct{
ElemType data[MaxSize];
int front,rear;
}SqQueue;
void InitQueue(SqQueue &Q)
{
memset(Q.data,'\0',MaxSize);
Q.rear=0;
Q.front=0;
}
bool Push(SqQueue &Q,ElemType x)
{
if(Q.front==(Q.rear+1)%MaxSize)return false;
Q.data[Q.rear]=x;
Q.rear=(Q.rear+1)%MaxSize;
return true;
}
bool Pop(SqQueue &Q,ElemType &x)
{
if(Q.front==Q.rear)return false;
x=Q.data[Q.front];
Q.front=(Q.front+1)%MaxSize;
return true;
}
bool QueueEmpty(SqQueue &Q)
{
if(Q.front==Q.rear)return true;
else return false;
}
void ImitatePort()
{
//我用一个字符串来保存等待上船车辆序列,越往左就越是先到达的,
char entry[10];
memset(entry,'\0',10);
printf("\n等待上船的汽车序列:\n");
scanf("%s",entry); //我以"T"表示货车,以"B"表示客车
int i=0,B=0;
SqQueue Q; //定义用来暂存货车的队列Q
InitQueue(Q);
printf("\n实际允许上船的汽车序列:\n");
ElemType x;
while(i<10)
{
if(B==4)
{
if(!QueueEmpty(Q))
{
Pop(Q,x);
printf("%c",x);
B=0;
}
}
if(entry[i]=='T')
{
Push(Q,'T');
}
else if(entry[i]=='B')
{
printf("B");
B++;
}
i++;
}
while(!QueueEmpty(Q))
{
Pop(Q,x);
printf("%c",x);
}
printf("\n");
}
int main()
{
ImitatePort(); //渡口模拟算法:
return 0;
}
(2)链式队列实现:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//顺序队列基本数据类型定义:
#define ElemType char
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct{
LinkNode *front,*rear;
}LiQueue;
void InitQueue(LiQueue &Q)
{
Q.front=(LinkNode*)malloc(sizeof(LinkNode));
Q.front->next=NULL;
Q.rear=Q.front;
}
void Push(LiQueue &Q,ElemType x)
{
LinkNode* p;
p=(LinkNode*)malloc(sizeof(LinkNode));
p->data=x;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}
bool Pop(LiQueue &Q,ElemType &x)
{
if(Q.front==Q.rear)return false;
LinkNode* p=Q.front->next;
Q.front->next=p->next;
if(Q.rear==p)Q.rear=Q.front;
x=p->data;
free(p);
return true;
}
bool QueueEmpty(LiQueue &Q)
{
if(Q.front==Q.rear)return true;
else return false;
}
void ImitatePort()
{
//我用一个字符串来保存等待上船车辆序列,越往左就越是先到达的,
char entry[10];
memset(entry,'\0',10);
printf("\n等待上船的汽车序列:\n");
scanf("%s",entry); //我以"T"表示货车,以"B"表示客车
int i=0,B=0;
LiQueue Q; //定义用来暂存货车的队列Q
InitQueue(Q);
printf("\n实际允许上船的汽车序列:\n");
ElemType x;
while(i<10)
{
if(B==4)
{
if(!QueueEmpty(Q))
{
Pop(Q,x);
printf("%c",x);
B=0;
}
}
if(entry[i]=='T')
{
Push(Q,'T');
}
else if(entry[i]=='B')
{
printf("B");
B++;
}
i++;
}
while(!QueueEmpty(Q))
{
Pop(Q,x);
printf("%c",x);
}
printf("\n");
free(Q.front);
Q.front=NULL;
Q.rear=NULL;
}
int main()
{
ImitatePort(); //渡口模拟算法:
return 0;
}
上面的两个代码都使用了一个队列。这与王道的视频的讲解不同