美文网首页
带与不带头结点的链式队列对比

带与不带头结点的链式队列对比

作者: lucas_cc | 来源:发表于2018-04-23 23:13 被阅读0次

    结论:对带头节点的链队列进行操作更加方便。

    • 不带头结点的链队列在入队第一个元素时需要特殊处理;
      先判断是否为空,再选择插入方式,而带头结点则不需要这步操作;

    分析如下:

    • 链式队列的存储类型可描述为:

    typedef struct {
        ElemType data;
        strcut LinkNode *next;
    } LinkNode;
    
    typedef struct {
        LinkNode *front;
        LinkNode *rear;
    } LinkQueue;
    

    1.带头节点的链式队列

    /* with a head node */
    /* initialize the queue */
    void InitQueue(LinkNode *Q)
    {
        /* creat a head node */
        Q->front = Q->rear = (LinkNode*)malloc(sizeof(LinkNode));
        Q->front->next = NULL;
    }
    
    /* judge whether the queue is empty */
    bool IsEmpty(LinkNode *Q)
    {
        if (Q->front == Q->rear) return true;
        else return false;
    }
    
    /* Push a element into the queue */
    void EnQueue(LinkQueue *Q, ElemType x)
    {
        LinkNode *S;
        S = (LinkNode*)malloc(sizeof(LinkNode));
        S->data = x;
        S->next = NULL;
        Q->rear->next = S;
        Q->rear = S;
    }
    
    /* Pop a element from the queue */
    bool DeQueue(LinkNode *Q, ElemType *x)
    {
        if (IsEmpty(Q)) return false;
        P = (LinkNode)malloc(sizeof(LinkNode));
        P = Q->front->next;
        *x = P->data;
        Q->front->next = P->next;
        if (Q->rear == P)
            Q->rear = Q->front;
        free(P);
        return true;
    }
    

    2.不带头结点的链式队列

    /* with no head node */
    /* initialize the queue */
    void InitQueue(LinkNode *Q)
    {
        Q->front = Q->rear = NULL;
    }
    
    /* judge whether the queue is empty */
    bool IsEmpty(LinkNode *Q)
    {
        if (Q->front == NULL) return true;
        else return false;
    }
    
    /* Push a element into the queue */
    void EnQueue(LinkQueue *Q, ElemType x)
    {
        LinkNode *S;
        S = (LinkNode*)malloc(sizeof(LinkNode));
        S->data = x;
        S->next = NULL;
        if (IsEmpty(Q)) {
            Q->front = Q->rear = S;
        } else {
            Q->rear->next = S;
            Q->rear = S;
        }
        return;
    }
    
    /* Pop a element from the queue */
    bool DeQueue(LinkNode *Q, ElemType *x)
    {
        if (IsEmpty(Q)) return false;
        P = (LinkNode)malloc(sizeof(LinkNode));
        P = Q->front;
        *x = P->data;
        if (Q->front == Q->rear) Q->front = Q->rear = NULL;
        else {
            Q->front = P->next;
        }
        free(P);
        return true;
    }
    

    相关文章

      网友评论

          本文标题:带与不带头结点的链式队列对比

          本文链接:https://www.haomeiwen.com/subject/tbdrlftx.html