队列的两种实现形式

链表实现

#include <cstdio>
#define null NULL
using namespace std;
struct node
{
    node* nxt;
    int val;
};
struct queue
{
    node* front;
    node* rear;
    queue()
    {
        front=rear=null;
    }
    void push(int val)
    {
        node* x = new node();
        x->val=val;
        x->nxt=null;
        if(rear==null)
        {
            front=x;
            rear=x;
        }
        else
        {
            rear->nxt=x;
            rear=x;
        }
    }
    void pop()
    {
        if(front==null)
            return;
        if(front==rear)
        {
            front=null;
            rear=null;
        }
        else
        {
            node* x=front;
            front=x->nxt;
            delete x;
        }
    }
    int empty()
    {
        return front==null;
    }
    int _front()
    {
        if(front==null)
            return 0;
        else
            return front->val;
    }
};
int main()
{
    queue q=queue();
    q.push(1);
    q.push(2);
    q.pop();
    q.push(3);
    q.push(4);
    q.push(5);
    q.pop();
    q.push(6);
    while(!q.empty())
    {
        int x =q._front();
        q.pop();
        printf("%d\n",x);//3 4 5 6
    }
}

数组实现

#include <cstdio>
#define null NULL
using namespace std;
struct queue
{
    int* q;
    int front;
    int rear;
    int maxsiz;
    int siz;
    queue(int _siz)
    {
        q=new int[_siz];
        front=rear=siz=0;
        maxsiz=_siz;
    }
    void push(int val)
    {
        if(siz==maxsiz)
        {
            printf("full\n");
            return;
        }
        else
        {
            q[rear]=val;
            rear=(rear+1)%maxsiz;
            siz++;
        }
    }
    int _front()
    {
        return q[front];
    }
    void pop()
    {
        front++;
        siz--;
    }
    bool empty()
    {
        return siz==0;
    }
};
int main()
{
    queue q= queue(10);
    q.push(1);
    q.push(2);
    q.pop();
    q.push(3);
    q.push(4);
    q.push(5);
    q.pop();
    q.push(6);
    while(!q.empty())
    {
        int x =q._front();
        q.pop();
        printf("%d\n",x);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值