java循环单链表:约瑟夫问题

java循环单链表:约瑟夫问题_第1张图片

import java.util.Scanner;

public class Josepfu_game_dome1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List l = new List();
		Scanner input = new Scanner(System.in);
		System.out.println("------------<<约瑟夫游戏>>----------");
		System.out.print("请输入参与者的个数:");
		int sum = input.nextInt();
		System.out.println("------------------------");
		System.out.printf("请输入开始的位置(1 到 %d):\t",sum);
		int start = input.nextInt();
		System.out.print("请输入相隔的位置:");
		int count = input.nextInt();
		
		l.add(sum);
		l.go(start,count,sum);
      
	}

}
//单向循环链表
class List{
	Hero head = null;
	public void add(int sum)
	{
		if(sum < 1)
		{
			System.out.println("人数不够");
			return;
		}
		Hero temp = null;
		for(int i = 1;i <= sum;i ++)
		{
			Hero hero = new Hero(i);//创建对象
			if(i == 1)
			{
				head = hero;
				hero.setNext(head);
				temp = head;
			}
			else
			{
				temp.setNext(hero);
				hero.setNext(head);
				temp = hero;
			}
		}
	}
	//遍历
	public void show()
	{
		if(head == null)
		{
			System.out.println("没有人");
			return;
		}
		Hero temp = head;
		while(true)
		{
			System.out.println(temp.getId() + "在圈中");
			if(temp.getNext() == head)
			{
				break;
			}
			temp = temp.getNext();
		}
	}
	//出圈
	/**
	 * 
	 * @param start:开始的位置
	 * @param count:要跳过的数目
	 * @param sum  :总人数
	 */
	public void go(int start,int count,int sum)
	{
		if(head == null || start < 1 || start > sum)
		{
			System.out.println("数据有误");
			return;
		}
		Hero temp = head;
		while(true)
		{
			if(temp.getNext() == head)
			{
				break;
			}
			temp = temp.getNext();
		}
		//到指定位置
		for(int i = 0;i < start - 1;i ++)
		{
			head = head.getNext();
			temp = temp.getNext();
		}
		//开始出圈
		while(true)
		{
			if(temp == head)
			{
				break;
			}
			for(int i = 0;i < count - 1;i ++)
			{
				head = head.getNext();
				temp = temp.getNext();
			}
			System.out.println(head.getId() + "出圈");
			head = head.getNext();//出圈后开始的结点指向下个结点
			temp.setNext(head);//直接跳过出圈的结点
		}
		System.out.println("最后" + head.getId() + "在圈中");
	}
}
//单个节点的信息
class Hero{
	private int id;//编号
	private Hero next;
	public Hero(int id)
	{
		this.id = id;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Hero getNext() {
		return next;
	}
	public void setNext(Hero next) {
		this.next = next;
	}
	
}

添加
java循环单链表:约瑟夫问题_第2张图片出圈
java循环单链表:约瑟夫问题_第3张图片

你可能感兴趣的:(java数据结构)