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;
		}
	}
}

你可能感兴趣的:(java)