java-13个坏人和13个好人站成一圈,数到7就从圈里面踢出一个来,要求把所有坏人都给踢出来,所有好人都留在圈里。请找出初始时坏人站的位置。...


import java.util.ArrayList;
import java.util.List;


public class KickOutBadGuys {

/**
* 题目:13个坏人和13个好人站成一圈,数到7就从圈里面踢出一个来,要求把所有坏人都给踢出来,所有好人都留在圈里。请找出初始时坏人站的位置。
* Maybe you can find out the mathematical rule behind the question.
* But we try to figure it out in Java.
* It's easy to have Circular Linked List in mind.
* Of course we can use Java's 'LinkedList'.
* But I implement my "Circular Linked List" for practice.
*/

private static final int MAX=26;
private static final int STEP=7;
private static final int NUM=13;//number of bad guys

public static void main(String[] args) {

int[] guys=new int[MAX];
for(int i=0;i<MAX;i++){
guys[i]=i;
}
Node head=initialCircularList(guys);
printCircularList(head);

List<Node> badGuys=new ArrayList<Node>();
head=kickOutBadGuys(head,badGuys);
printCircularList(head);

//print location of bad guys
System.out.print("locations of bad guys are:");
for(Node node:badGuys){
System.out.print(node.id+" ");
}

}

public static Node kickOutBadGuys(Node head,List<Node> list){
Node node=head;
Node previous=node;
int i=0;
while(i<NUM){
int step=STEP;
while(step>0){
previous=node;
node=node.next;
step--;
}
list.add(node);
previous.next=node.next;
i++;
}
return previous;//No matter what 'previous' is,we can traverse the 'CircularList',starting from 'previous'
}

public static Node initialCircularList(int[] data){
if(data==null||data.length==0){
return null;
}
int len=data.length;
Node tail=new Node(data[len-1]);
Node head=tail;
int i=len-2;
while(i>=0){
Node p=new Node(data[i]);
p.next=head;//尾插法
tail.next=p;
head=p;
i--;
}
return head;
}

public static void printCircularList(Node head){
if(head==null){
return;
}
System.out.print(head.id+" ");
Node node=head.next;
while(node!=null&&node!=head){//end condition is not "node.next==null" but "node==head"
System.out.print(node.id+" ");
node=node.next;
}
System.out.println();
}
private static class Node{
int id;
Node next;
Node(int id){
this.id=id;
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值