测试队列的长度

这篇博客介绍如何使用C++实现链表队列,并提供了初始化队列、入队操作以及计算队列长度的函数。通过创建链表结构的节点,实现了队列的基本操作。在主函数中,用户可以输入字符直到遇到'#',所有输入的字符被加入队列,最后输出队列的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<iostream>
using namespace std;
typedef char elemtype;
typedef struct node {
    elemtype data;
    struct node*next;
};
typedef struct LinkQueue {
    node* front;
    node* reat;
};
void initQueue(LinkQueue*q)                     //初始化队列
{
    q->front = q->reat = (node*)malloc(sizeof(node));
    if (!q->front)
        cout << "initQueue error" << endl;
    q->front->next = NULL;
}
void Enqueue(LinkQueue*q, elemtype e)        //往队列里写入数据
{
    node*p;
    p = (node*)malloc(sizeof(node));
    if (!q->front)
        cout << "error" << endl;
    p->data = e;
    p->next = NULL;
    q->reat->next = p;
    q->reat = p;
}
int getLen(LinkQueue*q)
{
    node* p;
    int count = 0;
    p = q->front;
    while (p!=q->reat)
    {
        count++;
        p = p->next;
    }
    return count;
}
int main()
{
    LinkQueue q;
    char e;
    initQueue(&q);
    cout << "input a string into a queue:" << endl;
    cin >> e;
    while (e != '#')
    {
        Enqueue(&q, e);
        cin >> e;
    }
    cout << "hte length of the queue is:" << getLen(&q) << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值