队列(数据结构篇)

数据结构之队列

队列(queue)

概念

  • 队列也是一种线性表,使用队列时插入在一端进行而删除则在另一端进行,队列的基本操作是入队,它是在表的末端(也叫做队尾)插入一个元素,出队,它是删除在**表的开头(**队头)的元素。

image

数组实现

//数组实现
class queue{
public:
    //入队(向数组末尾插入数据)
    void Push(int data){
        head.push_back(data);
    }

    //出队(将数组第一个元素删除)
    void Pop(){
        if(head.empty()){
            cout<<"队列中没有数据!"<<endl;
            return;
        } else{
            auto it=head.begin();
            head.erase(it);
        }
    }

    //获取队首元素
    int front(){
        if(head.empty()){
            cout<<"队列中没有数据!"<<endl;
            return NULL;
        }
        return head[0];
    }

    //打印队列
    void print(){
        if(head.empty()){
            cout<<"队列中没有数据!"<<endl;
            return;
        }
        for(int i:head){
            cout<<i<<" ";
        }
        cout<<endl;
    }

    //清空队列
    void destroy(){
        head.clear();
    }

    //获取队列大小
    int size(){
        return head.size();
    }

    //判断队列是否为空
    bool empty(){
        if(head.empty()){
            return true;
        } else{
            return false;
        }
    }

private:
    vector<int>head;
};

链表实现:

//链表实现
struct Queue{
    int data;
    Queue* next;
};

Queue* createNode(int data){
    auto p=new Queue;
    p->data=data;
    p->next=NULL;
    return p;
}

//入队
void push(Queue* &head,int data){
    Queue* add= createNode(data);
    if (head==NULL){
        head=add;
    }else{
        Queue* p=head;
        while (p->next!=NULL){
            p=p->next;
        }
        p->next=add;
    }
}

//出队
void pop(Queue* &head){
    if(head==NULL){
        cout<<"队列中没有元素"<<endl;
        return;
    }
    Queue* p=head;
    head=p->next;
    delete p;
}

//获取队首元素
int front(Queue* &head){
    if(head==NULL){
        cout<<"队列中没有元素"<<endl;
        return NULL;
    }
    return head->data;
}

//打印队列
void print(Queue* &head){
    if(head==NULL){
        cout<<"队列中没有元素"<<endl;
        return;
    }
    Queue* p=head;
    while (p!=NULL){
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}

//清空队列
void destroy(Queue* &head){
    if(head==NULL){
        cout<<"队列中没有元素"<<endl;
        return;
    }
    Queue* tail=head->next;
    while (head!=NULL){
        delete head;
        head=tail;
        if(tail!=NULL)
            tail=tail->next;
        else
            return;
    }
}

尾言

完整版笔记也就是数据结构与算法专栏完整版可到我的博客进行查看,或者在github库中自取(包含源代码)

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值