日期:2014-05-20  浏览次数:20732 次

约瑟夫环,语言翻译一下,有没有更但疼的翻译?
以下是java实现的版本:

Java code

import java.io.*;
import java.util.*;

public class YSF {
    
    static LinkedList<Integer> ysf = new LinkedList<Integer>();
    static int m;
    static int pos = -1;

    public static void main(String[] args) throws Exception {
        BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
        
        String line = rd.readLine();
        
        m = Integer.parseInt(rd.readLine());
        
        for (String str : line.split(" ")) {
            try {
                ysf.add(Integer.parseInt(str));
            } catch (Exception e) {
            }
        }
        
        for (;ysf.size() != 1; ysf.remove(pos--)) {
            pos = (pos + m) % ysf.size();
            m = ysf.get(pos);
            System.out.print(m + ",");
        }
        
        System.out.print(ysf.get(0) + "\n");
    }
}



用C语言翻译以后(注释的每一句话是java的后面紧接着是C语言实现):

C/C++ code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ysf[100];
int total = 0;

char line[256];
char line2[256];
int m;

int pos;

int ysf_get(int index)
{
    return ysf[index];
}

void ysf_remove(int index)
{
    int *p = ysf + index;
    int *q = p + 1;
    memmove(p, q, (total - index - 1) * sizeof (int));
    total--;
}

int main(void)
{
    //BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
    // none

    //String line = rd.readLine();
    fgets(line, sizeof (line), stdin);

    //m = Integer.parseInt(rd.readLine());
    m = strtol(fgets(line2, sizeof (line2), stdin), NULL, 10);

    //for (String str : line.split(" ")) {
    //    try {
    //        ysf.add(Integer.parseInt(str));
    //    } catch (Exception e) {
    //    }
    //}
    char *s, *str;
    for (s = line; NULL != (str = strtok(s, " ")); s = NULL)
    {
        ysf[total++] = strtol(str, NULL, 10);
    }

    //for (;ysf.size() != 1; ysf.remove(pos--)) {
    //    pos = (pos + m) % ysf.size();
    //    m = ysf.get(pos);
    //    System.out.print(m + ",");
    //}
    for (;total != 1; ysf_remove(pos))
    {
        pos = (pos + m) % total;
        m = ysf_get(pos);
        printf("%d,", m);
    }

    //System.out.print(ysf.get(0) + "\n");
    printf("%d\n", ysf_get(0));

    return 0;
}



------解决方案--------------------