队列 —— 链队列

队列

这里写图片描述

代码

/*
    function:queue
    created by : xilong
    date: 2017.2.9
*/

#include "iostream"
using namespace std;

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Elemtype;
typedef int Status;
typedef struct QNode
{
    Elemtype data;
    struct QNode* next;
} QNode, *QueuePrt;

typedef struct
{
    QueuePrt front, rear;
} LinkQueue;

/*
    initialize the queue
*/
Status Init_Queue(LinkQueue *q)
{
    q->front = q->rear = (QueuePrt)malloc(sizeof(QNode));
    if (!q->front)
        exit(0);
    q->front->next = NULL;
    return OK;
}

/*
    Insert an element into the queue, an element can only be inserted into the end of the queue 
*/
Status Inster_Queue(LinkQueue *q, Elemtype e)
{
    QueuePrt p;
    p = (QueuePrt)malloc(sizeof(QNode));
    if (p == NULL)
        exit(0);
    p->data = e;
    p->next = NULL;
    q->rear->next = p;
    q->rear = p;
    return OK;
}

/*
    Delete an element in the queue, an element which is in the front can only be deleted 
*/
Status Delete_Queue(LinkQueue *q, Elemtype *e)
{
    QueuePrt p;
    if (q->front == q->rear)
    {
        cout << "空队!" << endl;
        return FALSE;
    }
    p = q->front->next;
    q->front->next = p->next;
    if (q->rear == p)
    {
        q->rear = q->front;
    }
    *e = p->data;
    free(p);
    return TRUE;
}

/*
    length of the queue
*/
int Length_Queue(LinkQueue *q)
{
    QueuePrt p;
    int len = 0;
    p = q->front->next;
    if (q->front == q->rear)
        cout << "空队!" << endl;
    while (p)
    {
        len++;
        p = p->next;
    }
    return len;
}

void main()
{
    LinkQueue q;
    Elemtype e;
    int i, len;
    Init_Queue(&q);
    Inster_Queue(&q, 1);
    Inster_Queue(&q, 2);
    Inster_Queue(&q, 3);
    Inster_Queue(&q, 4);
    Inster_Queue(&q, 5);
    Inster_Queue(&q, 6);
    Inster_Queue(&q, 7);
    Inster_Queue(&q, 8);
    len = Length_Queue(&q);
    cout << "队列的长度为:";
    cout << len << endl;
    cout << "出对列的顺序为:";
    for (i = 0; i < len; i++)
    {
        Delete_Queue(&q, &e);
        cout << e << " ";
    }
    cout << endl;
    system("pause");
}

截图

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值