队列之链队列

感觉自己看的好慢啊,什么时候才能看到树和图啊~~~~~

本文介绍的是链队列。注意本文的链队列带有头结点,这是为了简化边界条件的处理。

对于出队操作,需要说明的是,在出队算法中,一般只需修改队头指针。但当原队中只有一个结点时,该结点既是队头也是队尾,故删去此结点时亦需修改尾指针。以下是代码,错误之处,还请指出!

#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;
}

测试样例:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值