第一题:约瑟夫环的问题:java类库中只有LinkedList,没有循环链表
//节点类
public class Node {
public int data;
public Node next;
public Node(int i){
data=i;
}
}
//循环链表类
public class CirList {
private Node tail;
private Node cur;
public Node head;
public int size;
//创建单向循环链表
public CirList(int n){
tail=new Node(n);
cur=tail;
for(int i=n-1;i>1;i--){
Node node=new Node(i);
node.next=cur;
cur=node;
}
head=new Node(1);
head.next=cur;
tail.next=head;
size=n;
}
//将要删除的元素放在第一个位置
public void setHeader(int s){
Node temp;
for(int i=1;i<s;i++){
temp=head;
head=head.next;
tail=temp;
}
}
//删除第一个位置的元素
public void delete(){
head=head.next;
tail.next=head;
size--;
} }
//主体类
import java.io.*;
public class Josephus {
public static void main(String args[]){
Josephus jsf=new Josephus();
try{
System.out.println("请输入人数:");
int n=Integer.valueOf(jsf.getString()).intValue();
System.out.println("请输入步长:");
int s=Integer.valueOf(jsf.getString()).intValue();
CirList list=new CirList(n);
while(list.size!=1){
list.setHeader(s);
list.delete();
}
System.out.println(list.head.data);
}catch(IOException e){
System.out.println("请输入数据");
}
}
public String getString() throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
} }
第二题:从键盘输入123456-->654321
import java.io.*;
public class Porblem2 {
public static void main(String args[]) throws IOException{
System.out.println("请输入要转换的数据:");
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader bu=new BufferedReader(in);
String s=bu.readLine();
StringBuffer sb=new StringBuffer(s);
System.out.println(sb.reverse());
}
}