队列,链队列,循环队列

队列:当然用c++

#include<bits/stdc++.h>
int main()
{
    std::queue<int> q;int x;
    while(scanf("%d",&x),x) q.push(x);
    std::cout<<q.size()<<"\n";
    while(!q.empty()) std::cout<<q.front()<<'\n',q.pop();
    return 0;
}

链队列:c语言实现

#include<bits/stdc++.h>
using namespace std;
typedef int QElemType;
typedef struct node
{
    QElemType data;
    struct node *next;
}QNode,*QueuePtr;
typedef struct
{
    QueuePtr front;
    QueuePtr rear;
}LinkQueue;
void InitQueue(LinkQueue &Q)//初始化队列
{
    Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));//先申请内存
    if(!Q.front) exit(0);
    Q.front->next=NULL;//下一个节点为空
}
void DestoryQueue(LinkQueue &Q)//销毁队列
{
    while(Q.front)//循环销毁
    {
        Q.rear=Q.front->next;
        free(Q.front);
        Q.front=Q.rear;
    }
}
void EnQueue(LinkQueue &Q,QElemType e)//插入队尾元素
{
    QNode *p;
    p=(QueuePtr)malloc(sizeof(QNode));
    if(!p) exit(0);
    p->data=e;
    p->next=NULL;
    Q.rear->next=p;//自己画图理解
    Q.rear=p;
}
QElemType DeQueue(LinkQueue &Q)
{
    QElemType e;
    QNode *p;
    if(Q.front==Q.rear) exit(0);
    p=Q.front->next;
    e=p->data;
    Q.front->next=p->next;
    if(Q.rear==p) Q.rear=Q.front;
    free(p);
    return e;
}
bool QueueEmpty(LinkQueue &Q)
{
    if(Q.front==Q.rear) return true;
    else return false;
}
int main()
{
    LinkQueue Q;
    InitQueue(Q);
    int x;
    while(scanf("%d",&x),x) EnQueue(Q,x);
    while(!QueueEmpty(Q)) cout<<DeQueue(Q)<<endl;
    return 0;
}

循环队列

#include<bits/stdc++.h>
using namespace std;
#define MAXQSIZE 100
typedef int QElemType;
typedef struct
{
    QElemType *base;
    int front;
    int rear;
}SqQueue;
void InitQueue(SqQueue &Q)
{
    Q.base=(QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
    if(!Q.base) exit(0);
    Q.front=Q.rear=0;
}
int QueueLength(SqQueue Q)
{
    return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
void EnQueue(SqQueue &Q,QElemType e)
{
    if((Q.rear+1)%MAXQSIZE==Q.front) exit(0);
    Q.base[Q.rear]=e;
    Q.rear=(Q.rear+1)%MAXQSIZE;
}
int DeQueue(SqQueue &Q)
{
    QElemType e;
    if(Q.front==Q.rear) exit(0);
    e=Q.base[Q.front];
    Q.front=(Q.front+1)%MAXQSIZE;
    return e;
}
bool QueueEmpty(SqQueue Q)
{
    if(Q.front==Q.rear) return true;
    else return false;
}
int main()
{
    SqQueue Q;
    InitQueue(Q);
    QElemType x;
    while(scanf("%d",&x),x) EnQueue(Q,x);
    cout<<QueueLength(Q)<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值