码迷,mamicode.com
首页 > 其他好文 > 详细

单链表实现队列

时间:2015-10-15 18:38:55      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>

typedef int queue_element_t;

typedef struct queue_node_s
{
    queue_element_t element;
    struct queue_node_s *restp;
}queue_node_t;

/*Queue front & rear pointer*/
typedef struct
{
    queue_node_t *frontp,
             *rearp;
    int size;         
}queue_t;

void add_to_q(queue_t *qp, queue_element_t ele)
{
    /*Keep queue front pointer*/
    if(qp->size == 0)
    {
        qp->rearp = (queue_node_t*)malloc(sizeof(queue_node_t));
        qp->frontp = qp->rearp;
    }
    /*Renew queue rear pointer*/
    else
    {
        qp->rearp->restp = (queue_node_t*)malloc(sizeof(queue_node_t));
        qp->rearp = qp->rearp->restp;
    }
    
    qp->rearp->element = ele;
    qp->rearp->restp = NULL;
    ++(qp->size);
}

queue_element_t remove_from_q(queue_t *qp)
{
    queue_node_t *to_freep;
    queue_element_t ans;
    
    to_freep = qp->frontp;
    ans = to_freep->element;
    qp->frontp = to_freep->restp;
    free(to_freep);
    --(qp->size);
    
    if(qp->size == 0)
        qp->rearp = NULL;
        
    return ans;    
}

int main(void)
{
    queue_t queue = {NULL, NULL, 0};
    
    add_to_q(&queue, 100);
    add_to_q(&queue, 200);
    add_to_q(&queue, 300);
    add_to_q(&queue, 400);

    int i;
    int sum = queue.size;
    
    for(i = 0; i < sum; i++)
        printf("%d\n", remove_from_q(&queue));
}

单链表实现队列

标签:

原文地址:http://www.cnblogs.com/xbon/p/4883048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!