图解约瑟夫问题

循环链解决约瑟夫问题

 详细解释,请见代码注释

package linkedList;

public class CircleLinkedListDemo
{
	public static void main(String[] args)
	{
		CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
		circleSingleLinkedList.addBoy(25);
		circleSingleLinkedList.show();
		
		circleSingleLinkedList.countBoy(1, 2, 25);
	}
}

//创建一个单向链表
class CircleSingleLinkedList
{
	//创建一个first节点,当前没有编号
	private Boy first = null;
	//添加一个小孩节点,构建成一个环形的链表
	public void addBoy(int nums)
	{
		if(nums < 1)
		{
			System.out.println("nums的值不正确~");
			return;
		}
		Boy curBoy = null; 
		//使用for来创建我们的环形链表
		for(int i = 1;i <= nums;i++)
		{
			//根据编号来创建
			Boy boy = new Boy(i);
			//如果是第一个小孩
			if(i == 1)
			{
				first = boy;
				first.setNext(first);
				curBoy = first;
			}
			else
			{
				curBoy.setNext(boy);
				boy.setNext(first);
				curBoy = boy;
			}
		}
	}
	
	//遍历当前环形链表
	public void show()
	{
		if(first == null)
		{
			System.out.println("链表为空~");
			return;
		}
		else
		{
			Boy curBoy = first;
			while(true)
			{
				System.out.println("小孩的编号 : " + curBoy.getNo());
				//说明已经遍历完毕
				if(curBoy.getNext() == first)
				{
					break;
				}
				curBoy = curBoy.getNext();  //curBoy后移
			}

		}
	}
	
	//约瑟夫环算法
	public void countBoy(int startNo, int countNum, int nums)
	{
		//先对数据进行校验
		if(first == null || startNo < 1 || startNo > nums)
		{
			System.out.println("参数输入有误,请重新输入~");
			return;
		}
		//创建辅助指针,帮助完成小孩出圈
		Boy helper = first;
		//需要一个辅助指针(变量)helper,事先应该指向环形链表的最后一个节点
		while(true)
		{
			if(helper.getNext() == first) {
				break;
			}
			helper = helper.getNext();
		}
		//小孩报数之前,先让first和helper移动startNo-1次
		for(int j=0;j<startNo-1;j++)
		{
			first = first.getNext();
			helper = helper.getNext();
		}
		//当小孩报数时,让first和helper指针同时后移m-1次,然后出圈
		//这里是一个循环操作,直到圈中只有一个节点
		while(true)
		{
			if(helper == first)  //圈中只剩一个节点
			{
				break;
			}
			//first、helper后移countNum-1次
			for(int j=0;j<countNum-1;j++)
			{
				first = first.getNext();
				helper = helper.getNext();
			}
			//这时first指向的节点,即出圈的节点
			System.out.printf("小孩%d出圈\n", first.getNo());
			//first指针后移
			first = first.getNext();
			helper.setNext(first);
		}
		System.out.println("最后留在圈中的小孩编号: " + first.getNo());
		
	}
	
}

//创建一个boy类,表示一个节点
class Boy
{
	private int no; //编号
	private Boy next;  //指向下一个节点
	public Boy(int no)
	{
		this.no = no;
	}
	public int getNo()
	{
		return no;
	}
	public void setNo(int no)
	{
		this.no = no;
	}
	public Boy getNext()
	{
		return next;
	}
	public void setNext(Boy next)
	{
		this.next = next;
	}
	
}

发布了246 篇原创文章 · 获赞 22 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/104682152