noj.11-循环右移

在这里插入图片描述
思路:
构造一个队列,队首元素出队再入队实现循环右移。这里使用循环队列。
完整代码:

#include <iostream>
using namespace std;
int n;
#define max (n+1)//牺牲了一个空间
typedef struct
{
    
    
    int a[100];
    int len;
    int front;
    int rear;
}queue;
//初始化
void initqueue(queue *q)
{
    
    
  q->front=q->rear=0;
  q->len=0;
}
//入队
int enterqueue(queue *q,int x)
{
    
    
    if((q->rear +1)%max==q->front)
        return 0;
    q->a[q->rear]=x;
    q->rear=(q->rear +1)%max;
    q->len++;
    return true;
}
//出队
int outqueue(queue *q,int x)
{
    
    
    if(q->rear==q->front)
        return false;
    x=q->a[q->front];
    q->front=(q->front+1)%max;
    q->len--;
    return x;
}
//输出队列元素
void pop(queue *q)
{
    
    
    for(int i=1;i<=q->len;i++)
    {
    
    
        cout<<q->a[q->front]<<" ";
        q->front=(q->front+1)%max;
    }
}
//获得队首元素
int firstqueue(queue *q,int x)
{
    
    
    if(q->rear==q->front)
        return false;
    x=q->a[q->front];
    return x;
}
//队是否满
int isfull(queue *q)
{
    
    
    if((q->rear +1)%max==q->front)
        return 1;
    else
        return 0;
    return 0;
}
int main()
{
    
    
    int k,number;
    cin>>n>>k;
    queue q;
    initqueue(&q);
    int i;
    for(i=0;i<n;i++)
    {
    
    
        cin>>number;
        enterqueue(&q,number);
    }
   int x;
   if(k<n)
   {
    
    
     //注意此处的判断条件不是i<k!
     for(i=0;i<n-k;i++)
     {
    
    
         x=outqueue(&q,x);
         enterqueue(&q,x);
     }
     pop(&q);
   }
    else if(k==n)
    {
    
    
        pop(&q);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_50932477/article/details/116212392