[置顶] 剑指OFFER之队列

#include <stdio.h>
#include <malloc.h>
#include "common_define.h"
#include "jianzhioffer_queue.h"

status init_queue(struct linked_queue *Q)
{
    (*Q).front = (*Q).rear = NULL;

    return OK;
}

int queue_empty(struct linked_queue Q)
{
    if (!Q.rear && !Q.front)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

status push_queue(struct linked_queue *Q, q_elemtype elem)
{
    struct QNode *p;

    p = (struct QNode*)malloc(sizeof(struct QNode));
    if (!p)
    {
        return ERROR;
    }

    p->data = elem;
    p->next = NULL;
 
    if (queue_empty(*Q))
    {
        (*Q).front = (*Q).rear = p;
    }
    else
    {
        (*Q).rear->next = p; 
        (*Q).rear = p;
    }
   
    return OK;
} 

status pop_queue(struct linked_queue *Q, q_elemtype *elem)
{
    struct QNode *p;

    if (queue_empty(*Q))
    {
        return ERROR;
    }
    else
    {
        p = (*Q).front;
        (*elem) = p->data;
        (*Q).front = p->next;

        if (!p->next)
        {
            (*Q).rear = NULL;
        }

        free(p);

        return OK;
    }
}

你可能感兴趣的:([置顶] 剑指OFFER之队列)