约瑟夫环的java实现


import java.io.*;
 class Node{
 private int data[] = new int[2];
 private Node link;
 private static int count = -1;
 
 public Node(int data){
  this.data[0] = data;
  this.data[1] = ++count;
  link = null;
 }  
 public void setData(int data){
  this.data[0] = data;
 }
 public int getData(){
  return data[0]; 
 }
 public int getCount(){
  return data[1]; 
 }
 public void setLink(Node link){
  this.link = link; 
 }
 public Node getLink(){
  return link; 
 }
}

 class LinkList{
 public Node head;
 public Node last;
 
 public LinkList(int data){
  head = new Node(data);
  head.setLink(head);
  last = head;
 } 
 public String vistAllNode(){
  Node next = head;
  String s = new String();
  do{
   s = s + next.getData() + "  ";
   next = next.getLink();  
  }while(next != head);
  return s; 
 }
 public boolean removeNode(Node node){  //去掉node的下一个结点
  if(node == last){
   head = head.getLink();
   last.setLink(head);
  }
  else if(node.getLink() == last){
   last = node;
   last.setLink(head); 
  }
  else{
   Node tempN = node.getLink();
   tempN = tempN.getLink();
   node.setLink(tempN); 
  }
   
  return true;
 }
 public boolean removeAll(){
  head.setLink(head);
  last = head;
  head.setData(0);
  return true; 
 }
 public void append(int data){
  Node temp = new Node(data);
  last.setLink(temp);
  last = temp;
  last.setLink(head); 
 }
}


public class 约瑟夫环{
 private static LinkList link = new LinkList(0);
 private static int inCount;
 private static int resultInCount;
  
 public static void main(String []args) throws IOException{
  int enter;
  String inputString = new String();
  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("这个程序是解决约瑟夫环的问题。/n请输入人数>>:");
  inCount = Integer.parseInt(input.readLine());
  System.out.print("请输入初始密码>>");
  int m = Integer.parseInt(input.readLine());
  System.out.println("请输入每个人的密码>>");
  for(resultInCount = 0; resultInCount < inCount; resultInCount++){
   inputString = input.readLine();
   enter = Integer.parseInt(inputString);
   link.append(enter); 
  }
  link.removeNode(link.last);
  
  Node p = link.head, q = link.last;
  int i = 0;
  int j = 0;
  for(;;){
   i++;
   if(i == m){
    i = 0;
    m = p.getData();
    System.out.print(p.getCount()+"  ");
    link.removeNode(q);
    p = p.getLink();
    j++;
    if(j == inCount) break;
    continue;
   }
   q = q.getLink();
   p = q.getLink();
     
  } 
  
 } 
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值