感觉自己看的好慢啊,什么时候才能看到树和图啊~~~~~
本文介绍的是链队列。注意本文的链队列带有头结点,这是为了简化边界条件的处理。
对于出队操作,需要说明的是,在出队算法中,一般只需修改队头指针。但当原队中只有一个结点时,该结点既是队头也是队尾,故删去此结点时亦需修改尾指针。以下是代码,错误之处,还请指出!
#include<cstdio>
#include<cstdlib>
typedef char Datatype; //假定队列元素的数据类型为字符
typedef struct node{ //队列结点类型
Datatype data;
struct node *next;
}QueueNode;
typedef struct{ //将队头和队尾指针合在一起
QueueNode *front; //队头、队尾指针
QueueNode *rear;
}LinkQueue;
void InitQueue(LinkQueue *Q){ //构造一个空队列Q
Q->front=Q->rear=(QueueNode *)malloc(sizeof(QueueNode)); //生成头结点
if(!Q->front) //生成头结点失败
exit(0);
Q->front->next=NULL; //头结点的next域为空
}
bool QueueEmpty(LinkQueue *Q){
//若队列Q为空队列,则返回TRUE;否则返回FALSE
if(Q->front->next==NULL)
return true;
else
return false;
}
int QueueLength(LinkQueue *Q){ //求队列Q的长度
int i=0; //计数器,初值为0
QueueNode *p=Q->front; //p指向头结点
while(Q->rear!=p){ //p所指不是尾结点
i++; //计数器+1
p=p->next; //p指向下一个结点
}
return i;
}
Datatype QueueFront(LinkQueue *Q){
//若队列Q不空,则用e返回Q的队头元素,并返回OK;否则返回ERROR
if(QueueEmpty(Q)){ //如果队列空
printf("Queue is empty!\n");
exit(0);
}
QueueNode *p=Q->front->next; //p指向队头结点
return p->data;
}
void EnQueue(LinkQueue *Q,Datatype e){
// 插入元素e为队列Q的新的队尾元素。
QueueNode *p=(QueueNode *)malloc(sizeof(QueueNode)); //生成新结点
if(!p)
exit(0); //失败则退出
p->data=e; //将值e赋给新结点
p->next=NULL; //新结点的指针域为空
Q->rear->next=p; //原队尾结点的指针指向新结点
Q->rear=p; //尾指针指向新结点
}
void DeQueue(LinkQueue *Q){
// 若队列Q不空,删除Q的队头元素
QueueNode * p;
if(QueueEmpty(Q)) //队列空
exit(0);
p=Q->front->next; //p指向队头结点
Q->front->next=p->next; //头结点指向下一个结点
if(Q->rear==p) //删除的是队尾结点(形成空队列)
Q->rear=Q->front; //需要修改队尾指针指向头结点
free(p); //释放队头结点
}
void CreateQueue(LinkQueue *Q){
//建立一个队列
char ch;
while((ch=getchar())!='\n'){
EnQueue(Q,ch);
}
return ;
}
//*************************测试代码********************************
int main(){
LinkQueue *Q;
InitQueue(Q);
printf("输入一个字符串,来建立一个字符链队列:\n");
CreateQueue(Q);
printf("队列已建好,队列的元素个数是:%d\n",QueueLength(Q));
printf("队列头元素是:%c\n",QueueFront(Q));
printf("弹出队列顶元素:\n");
DeQueue(Q);
printf("此时队列头元素为:%c\n",QueueFront(Q));
printf("将元素‘z’进队列:\n");
EnQueue(Q,'z');
printf("此时队列顶元素是:%c\n",QueueFront(Q));
return 0;
}
测试样例: