搜索
您的当前位置:首页正文

环形链表解决约瑟夫问题

来源:易榕旅网

一.问题描述

二.创建环形链表

图解

代码实现
package fun.xinghai.linkedlist;

public class CircleSingleList {
	public SingleNode first = null;
	public SingleNode helper = null;
	
	/**
	 * 创建环形链表
	 * @param num 结点个数
	 */
	public void creat(int num) {
		if(num < 0) {
			System.out.println("输入结点个数有误!");
			return;
		}
		SingleNode curent = null; 
		for(int i = 1; i <= num; i++) {
			SingleNode node = new SingleNode(i);
			if(i == 1) {
				first = node;
				first.next = first;
				curent = first;
			}else {
				curent.next = node;
				node.next = first;
				curent = node;
			}
			if(i == num) {
				helper = curent;
			}
		}
	}
	
	public void move(int start) {
		for(int i = 0; i < start - 1; i++) {
			first = first.next;
			helper = helper.next;
		}
	}
	
	public void action(int step) {
		while(true) {
			if(helper == first) { //说明圈中只有一个节点
				break;
			}
			for(int i = 0; i < step - 1; i++) {
				first = first.next;
				helper = helper.next;
			}
			System.out.println("no:" + first.no + "出圈!");
			first = first.next;
			helper.next = first;
		}
		System.out.println("获胜者:no:" + first.no);
	}
	
	public void print() {
		SingleNode curent = first;
		while(true) {
			System.out.println("no:" + curent.no);
			if(curent.next == first) {
				break;
			}
			curent = curent.next;
		}
	}
	
}

class SingleNode{
	public int no;
	public SingleNode next;
	
	public SingleNode(int no) {
		this.no = no;
	}
}

三.解决约瑟夫问题

图解

代码实现
package fun.xinghai.linkedlist;

public class Josephu {

	public static void main(String[] args) {
		CircleSingleList circleSingleList = new CircleSingleList();
		circleSingleList.creat(4); //创建4个玩家的环形链表
		circleSingleList.print();
		System.out.println("============");
		circleSingleList.move(2); //从第2个玩家开始数数
		circleSingleList.action(2); //每次数2步
	}

}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top