编程语言
首页 > 编程语言> > java学习 使用循环链表解决约瑟夫问题

java学习 使用循环链表解决约瑟夫问题

作者:互联网

public class Josefu {

	public static void main(String[] args) {
		CirSingleLinked cir = new CirSingleLinked();
		//500个小孩
		cir.addBoy(500);
		//从第一个开始数,每数到3,出圈
		cir.countBoy(1, 3, 500);
		
	}

}

class CirSingleLinked {
	private Boy first = null;

	public boolean isEmpty() {
		return first == null;
	}

	public void list() {
		if (isEmpty()) {
			System.out.println("链表为空!");
			return;
		}

		Boy curBoy = first;

		while (true) {
			System.out.println(curBoy);
			if (curBoy.getNext() == first)
				break;
			curBoy = curBoy.getNext();
		}

	}

	// 添加小孩节点
	public void addBoy(int nums) {
		if (nums < 1) {
			System.out.println("请输入大于0的数");
			return;
		}

		// 辅助指针,帮助构建环形链表
		Boy curBoy = null;
		for (int i = 1; i <= nums; i++) {
			if (i == 1) {
				// 第一个结点next指向自己
				first = new Boy(i);
				first.setNext(first);
				curBoy = first;
				continue;
			}
			// 生成新的Boy结点
			Boy newBoy = new Boy(i);
			curBoy.setNext(newBoy);
			newBoy.setNext(first);
			curBoy = newBoy;

		}
	}

	/**
	 * 需创建一个辅助指针来进行出圈 
	 * @param startNo           从第几个小孩开始数数
	 * @param countNum          表示 数几下
	 * @param nums表示最初有多少个小孩在圈中
	 */
	public void countBoy(int startNo, int countNum, int nums) {

		if (first == null || startNo < 1 || startNo > nums) {
			System.out.println("数据录入有误,请重新输入");
			return;
		}
		//first 指向startNo小孩 移动 startNo-1次
		for (int i = 1; i < startNo; i++) {
			first = first.getNext(); 
		}
		
		//出圈
		//循环操作 直到圈中只有一个结点
		while(true) {
			if(first.getNext() == first) break;
			//小孩报数时, first移动到要删除的小孩前一位值,然后删除
			for(int i = 1; i< countNum -1 ;i++) {
				first = first.getNext();
				
			}
			
			System.out.println(first.getNext());
			first.setNext(first.getNext().getNext());
			first = first.getNext();

		}
		System.out.println(first);
	}
	
}

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

	@Override
	public String toString() {
		return "Boy [no=" + no + "]";
	}

}

标签:getNext,Boy,java,no,int,约瑟夫,链表,public,first
来源: https://blog.csdn.net/m0_47621042/article/details/110352399