队列(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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42513339/article/details/81270214