初学,写了个java的约瑟夫环,请大家给点意见!谢谢!!
import java.io.*;
class Node
{
int flag;//序号
Node next; //指针
int mima; //密码
public Node(int m,int n)
{
flag=m;
mima=n;
}
}
public class Yuesefu3
{
public static void main(String[] args)
{
int s=0,m1=0,m2=0,m3=0;
System.out.print( "请输入总数: ");
try
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String br=stdin.readLine();
s=Integer.parseInt(br);
}
catch(Exception ex)
{
System.out.print(ex);
}
System.out.println( "总数为: "+s);
System.out.print( "输入第1个人的密码为: ");
try
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String br=stdin.readLine();
m1=Integer.parseInt(br);
}
catch(Exception ex)
{
System.out.println(ex);
}
Node a1=new Node(1,m1);
Node index=a1;
for(int i=2;i <=s;i++) //初始化每个人
{
System.out.print( "请输入第 "+i+ "个人的密码: ");
try
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String br=stdin.readLine();
m2=Integer.parseInt(br);
}
catch(Exception e)
{
System.out.println(e);
}
index.next=new Node(i,m2);
index=index.next;
}
index.next=a1;
System.out.print( "请输入初始密码: ");
try
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String br=stdin.readLine();
m3=Integer.parseInt(br);
}
catch(Exception e)
{
System.out.println(e);
}
for(int i=0;i <s;i++)
{
for(int j=0;j <m3-1;j++) //轮转查询
{
index=index.next;
}
System.out.println( "第 "+index.next.flag+ "人出局 ");
m3=index.next.mima;
index.next=index.next.next;
}
}
}
------解决方案--------------------看看这个
main()
{
int i,test,p[17],head;
for(i=0;i <16;i++)
p[i]=i+1;
p[16]=0;
test=0;
while(test!=p[test])
{
for(i=1;i <3;i++)
{
head=test;
test=p[test];
}
p[head]=p[test];
test=p[head];
}
printf( "\n%5d ",test);
------解决方案--------------------学习,长见识了。