循环队列(Joseplus Problem)

循环队列(Joseplus Problem)循环队列(Joseplus Problem)
#include <iostream>
#include <stdio.h>

using namespace std;

int Q[100];
int Head, Tail, Number_of_Items = 0;

void Enqueue(int x)
{
    if( Number_of_Items == 0 )
    {
        Head = Tail = 0;
        Q[0] = x;
    }
    else
    {
        Tail = (Tail + 1) % 100;//循环
        Q[Tail] = x;
    }
    Number_of_Items++;
}

int Dequeue()
{
    int z;

    z = Q[Head];
    Head = (Head + 1) % 100;
    Number_of_Items--;

    return z;
}

int main()
{
    int n;
    int i,j;
    int answer;

    printf("Enter an integer (1--99): ");
    scanf("%d", &n);

    /* Solve Joseplus Problem */
    /* Step 1: Put all the numbers beween 1 and n to the Queue */
    for(i = 1; i <= n; i++)
        Enqueue(i);

    /* Step 2: Start killing for n-1 rounds */
    for(i = 1; i <= n-1; i++)
    {
        j = Dequeue();
        Dequeue();
        Enqueue(j);
    }

    answer = Q[Head];

    printf("The value of J(%d) is: %d\n", n, answer);
    return 0;
}
View Code

相关推荐