经典的数据结构——循环队列

用数组实现循环队列,关键在于,如何实现头指针和尾指针的循环,揭秘如下:

front = ( front + 1) % MAX;
rear = ( rear + 1) % MAX;

代码如下:  

#include <QCoreApplication>
#include <iostream>

using namespace std;

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


#include <stdio.h>

#define MAX 5

/*Declaration of circular queue.*/
typedef struct
{
    int front   ;
    int rear    ;
    int count   ;
    int ele[MAX]    ;
}CirQueue;

/*Initailization of circular queue.*/
void initCirQueue(CirQueue * q)
{
    q->front =  0;
    q->rear  = -1;
    q->count =  0;
}

/*Check Queue is full or not*/
int isFull(CirQueue * q)
{
    int full=0;

    if(q->count == MAX)
        full = 1;

    return full;
}

/*Check Queue is empty or not*/
int isEmpty(CirQueue * q)
{
    int empty=0;

    if(q->count == 0)
        empty = 1;

    return empty;
}

/*To insert item into circular queue.*/
void insertCirQueue(CirQueue * q, int item)
{
    if( isFull(q) )
    {
        printf("\nQueue Overflow");
        return;
    }

    q->rear = (q->rear+1)%MAX;
    q->ele[q->rear] = item;

    q->count++;

    printf("\nInserted item : %d",item);
}

/*To delete item from queue.*/
int deleteCirQueue(CirQueue * q, int *item)
{
    if( isEmpty(q) )
    {
        printf("\nQueue Underflow");
        return -1;
    }

    *item    = q->ele[q->front];

    q->front = (q->front+1)%MAX;

    q->count--;

    return 0;
}


int main()
{
    int item=0;
    CirQueue q;

    initCirQueue(&q);

    insertCirQueue(&q, 10);
    insertCirQueue(&q, 20);
    insertCirQueue(&q, 30);
    insertCirQueue(&q, 40);
    insertCirQueue(&q, 50);
    insertCirQueue(&q, 60);

    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);


    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);


    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);


    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);


    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);

    insertCirQueue(&q, 60);

    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);


    if ( deleteCirQueue( &q, &item ) == 0 )
        printf("\nDeleted item is : %d",item);

    printf("\n");
    return 0;
}





代码都可以运行。




-----------------

阅读更多
想对作者说点什么? 我来说一句

循环队列打印Fibonacci

2010年11月13日 713KB 下载

数据结构 循环队列c++源代码

2008年11月25日 2KB 下载

没有更多推荐了,返回首页

不良信息举报

经典的数据结构——循环队列

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭