队列的创建、入队、出队、打印、统计队列长度

队列是一种特殊的线性表,在这种线性表中,删除运算限定在表的一段进行,而插入运算限定在表的另一端进行,通常,约定把允许插入的一端称为队尾,把允许删除的一端称为队首。队列进出的原则是先进队的先出队,即先进先出原则。队列在计算机程序设计中经常被用到,如Windows操作系统的消息队列。

队列可以采用链式或顺序存储结构来描述,本文采用链式结构来进行表达。由于队列需要在队首以及队尾进行删除和插入操作,所以需要设置两个指针来表示队列,通常队尾指针指向最后进入队列的元素,为了便于表示空队列,专门设置了一个头结点,当队列为空时,头指针和尾指针均指向头结点

本文示例中的函数功能包括队列的创建、入队、出队、打印、统计队列长度。

#include <iostream>

using namespace std;

struct node         //队列的节点
{
    int data;
    struct node *next;
};

struct linkQueue
{
    struct node *font;      //分别指向队列的头和尾
    struct node *rear;
    int n;      //队列长度
};

//创建一个空队列
void create(struct linkQueue *Q)
{
    //创建一个头节点
    struct node *head = new node;
    head->next = NULL;
    Q->font = head;
    Q->rear = head;
    Q->n = 0;
};

//入队数据num
void queueInsert(struct linkQueue *Q, int num)
{
    struct node *p = new node;
    p->data = num;
    p->next = NULL;
    Q->rear->next = p;
    Q->rear = p;
    Q->n++;
};

//出队并打印出队的数据
void queuePop(struct linkQueue *Q)
{
    struct node *temp;
    if(Q->font->next != NULL)
    {
        temp = Q->font->next;
        Q->font->next = Q->font->next->next;
        cout<<temp->data<<endl;
        delete(temp);
        if(Q->font->next == NULL)
            Q->rear = Q->font;
        Q->n--;
    }
};

//打印
void print(struct linkQueue *Q)
{
    cout<<"打印开始!"<<endl;
    struct node *temp = Q->font;
    if(temp == Q->rear)
        cout<<"队列为空!"<<endl;
    else
    {本文
         while(temp != Q->rear)
        {
            cout<<temp->next->data<<endl;
            temp = temp->next;
        }
    }
    cout<<"打印结束!"<<endl;
    cout<<endl;
}

int main()
{
    linkQueue Q;
    create(&Q);
    /********入队*************/
    queueInsert(&Q, 1);
    queueInsert(&Q, 2);
    queueInsert(&Q, 3);
    queueInsert(&Q, 4);
    print(&Q);
    /********出队*************/
    queuePop(&Q);
    print(&Q);
    queuePop(&Q);
    print(&Q);
    queuePop(&Q);
    print(&Q);
    queuePop(&Q);
    print(&Q);
    return 0;
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值