数据结构-队列

数组实现队列

//数组实现队列
#include<bits/stdc++.h>
using namespace std;
int n;
int q[100010];
int rear, front = 1;
char c[10];

int main(){
    cin >> n;
    for (int i = 1; i <= n; i++){
        scanf("%s", c);
        if (c[2] == 's'){
            int x;
            cin >> x;
            q[++rear] = x;
        }
        else if (c[0] == 'q'){
            int k;
            cin >> k;
            printf("%d\n", q[front + k - 1]);
        }
        else {
            front++;
        }
    }
    return 0;
}

队列练习

//队列练习
#include<bits/stdc++.h>
using namespace std;
int x, k;
int q[200010];
int rear = 0, front = 1;

int main(){
    scanf("%d%d", &x, &k);
    q[++rear] = x;
    for (int i = 1; i <= k; i++){
        q[++rear] = 2 * q[front];
        q[++rear] = 2 * q[front] + 1;
        printf("%d\n", q[front]);
        front++;
    }
    return 0;
}

排队买票

//排队买票
#include<bits/stdc++.h>
using namespace std;
int n;
int a[1010], b[1010];
int q[1000010];
int rear, front = 1;

int main(){
    scanf("%d", &n);
    for (int i = 1; i <= n; i++){
        int x;
        scanf("%d", &x);
        a[i] = x;
        q[++rear] = i;
    }
    int cnt = n;
    for (int i = 1; cnt; i++){
        a[q[front]]--;
        if (!a[q[front]]){
            b[q[front]] = i;
            cnt--;
        }
        else {
            q[++rear] = q[front];
        }
        front++;
    }
    for (int i = 1; i <= n; i++){
        printf("%d ", b[i]);
    }
}

约瑟夫问题

//约瑟夫问题
#include<bits/stdc++.h>
using namespace std;
int n, m;
int q[10010];
int rear, front = 1;

int main(){
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++){
        q[++rear] = i;
    }
    int cnt = n;
    for (int i = 1; cnt; i++){
        if (i % m == 0){
            printf("%d ", q[front]);
            cnt--;
        }
        else {
            q[++rear] = q[front];
        }
        front++;
    }
}

总结

和栈一样,STL中的queue只能取队首和删除队首,不能在队列中间进行操作,没有特殊情况下,尽量时候数组进行队列操作

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值