再做2个面试题目:(约瑟夫环)

 第一题:约瑟夫环的问题: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());
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值