首页 > 其他 > 详细

每日一题19:循环队列

时间:2015-04-08 23:24:27      阅读:332      评论:0      收藏:0      [点我收藏+]

基于数组实现的循环队列,这个比基于链表实现的稍微麻烦一点,需要浪费一个存储空间。如果全部利用,则编程将会变得更加繁琐,并且更容易出错。

// LoopQueue.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;

struct loop_queue
{
    int capacity;
    int head;
    int tail;
    int *vals;
};

loop_queue* create(int capacity)
{
    loop_queue* lq = new loop_queue;
    lq->capacity = capacity;
    lq->vals = new int[capacity];
    lq->head = lq->tail = 0;
    return lq;
}

bool isEmpty(loop_queue* lq)
{
    if(lq->head == lq->tail) return true;
    return false;
}

bool isFull(loop_queue* lq)
{
    if((lq->tail + 1) % lq->capacity == lq->head) return true;
    return false;
}

bool insert(loop_queue** lq,int val)
{
    if(!isFull(*lq))
    {
        (*lq)->vals[((*lq)->tail)] = val;
        (*lq)->tail = ((*lq)->tail + 1) % (*lq)->capacity;

        return true;
    }
    return false;
}

bool pop(loop_queue** lq,int &val)
{
    if(!isEmpty(*lq))
    {
        val = (*lq)->vals[((*lq)->head)];
        (*lq)->head = ((*lq)->head + 1) % (*lq)->capacity;
        return true;
    }
    return false;
}

bool get_front(loop_queue* lq,int& val)
{
    if(!isEmpty(lq))
    {
        val = lq->vals[lq->head];
        return true;
    }
    return false;
}

测试代码:

int _tmain(int argc, _TCHAR* argv[])
{
    loop_queue* lq = create(5);
    for (int i = 1; i < 11; ++i)
    {
        cout<<insert(&lq,i)<<‘ ‘;
    }
    cout<<endl;

    for (int i = 1; i < 4; ++i)
    {
        int val;
        cout<<pop(&lq,val)<<‘ ‘;
    }
    cout<<endl;

    for (int i = 1; i < 11; ++i)
    {
        cout<<insert(&lq,i)<<‘ ‘;
    }
    cout<<endl;

    for (int i = 1; i < 11; ++i)
    {
        int val;
        cout<<pop(&lq,val)<<‘ ‘;
    }
    cout<<endl;
    cout<<lq->head<<‘ ‘<<lq->tail<<endl;
    for (int i = 1; i < 11; ++i)
    {
        cout<<insert(&lq,i)<<‘ ‘;
    }
    cout<<endl;
    return 0;
}

每日一题19:循环队列

原文:http://blog.csdn.net/liao_jian/article/details/44948071

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!