队列(Queue)——(三)动态链式实现补充(不带头节点版本 )

不带头节点个人感觉比带头节点难理解些,带头节点也好用一些,带头节点的版本请点击这里。这里我就只贴一下实现代码。(C++)

myqueue.h

//不带头点节版本
typedef struct  _QNode
{
    char _data;
    struct  _QNode * _next;
}QNode;

typedef struct _Queue
{
    QNode *_front;
    QNode *_rear;
}Queue;

void initQueue(Queue * pq);
bool isQueueEmpty(Queue * pq);
void enQueue(Queue * pq,char data);
char deQueue(Queue * pq);
void clearQueue(Queue * pq);

 

myqueue.cpp

#include "myqueue.h"
#include <stdio.h>
#include <stdlib.h>
//不带头点节版本
void initQueue(Queue * pq)
{
    pq->_front = pq->_rear = NULL;
}
bool isQueueEmpty(Queue * pq)
{
    if(pq->_front == pq->_rear && pq->_front == NULL)
        return 1;
    else
        return 0;
}
void enQueue(Queue * pq,char data)
{
    if(isQueueEmpty(pq)) {
        pq->_front = (QNode*)malloc(sizeof(QNode));
        pq->_front->_data = data;
        pq->_rear = pq->_front;
        pq->_rear->_next = NULL;
    }
    else{

        QNode *cur = (QNode*)malloc(sizeof(QNode));
        cur->_data = data;
        cur->_next = NULL;
        pq->_rear->_next = cur;
        pq->_rear = cur;
    }

}
char deQueue(Queue * pq)
{
    char data;
    if(pq->_front == pq->_rear){
        data = pq->_front->_data;
        free(pq->_front);
        pq->_rear = pq->_front = NULL;

    }
    else
    {
        data = pq->_front->_data;
        QNode *t = pq->_front;
        pq->_front = pq->_front->_next;
        free(t);
    }
    return data;
}

void clearQueue(Queue * pq)
{
    if(isQueueEmpty(pq))
        return ;
    QNode *t;
    while(pq->_front)
    {
        t = pq->_front;
        pq->_front = pq->_front->_next;
        free(t);
    }
}


 

main函数

#include <iostream>
#include"myqueue.h"
using namespace std;
int main()
{
    Queue q;
    initQueue(&q);
    for(char ch='A';ch<='Z';ch++)
        enQueue(&q,ch);
    while(!isQueueEmpty(&q))
        printf("%c ",deQueue(&q));
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值