数据结构:单向环形链表

 约瑟夫问题



public class Josephus {
	public static void main(String[] args){
		SingleCircleLinkedList single = new SingleCircleLinkedList();
		single.addBoyNode(5);
		single.showNodes();
		single.countNode(1, 2, 5);
	}
}

class SingleCircleLinkedList{
	// 创建first节点
	private BoyNode first = null;
	
	public void addBoyNode(int nums){
		if(nums < 1){
			System.out.println("nums的值不正确");
			return;
		}
		
		BoyNode temp = null; // 辅助节点
		for(int i=1;i<=nums;i++){
			BoyNode bn = new BoyNode(i);
			if(i == 1){
				first = bn;
				first.setNext(first);
				temp = first;
			}else{
				temp.setNext(bn);
				bn.setNext(first);
				temp = bn;
			}
		}
	}
	
	// 遍历当前环形链表
	public void showNodes(){
		
		if(null == first){
			return;
		}
		
		BoyNode temp = first;
		do{
			System.out.println(temp.getNo());
			temp = temp.getNext();
		}while(first != temp);
	}
	
	/**
	 * startNo:从哪个位置开始数
	 * countNum 数几次
	 * nums:一共几个人 
	 */
	public void countNode(int startNo, int countNum, int nums){
		if(null == first || startNo<1 || startNo>nums){
			System.out.println("参数输入有误,请重新输入");
			return;
		}
		
		BoyNode helper = first;//辅助节点
		while(true){
			if(helper.getNext() == first){
				break;
			}
			helper = helper.getNext();
		}
		for(int j=0; j<startNo-1;j++){
			first = first.getNext();
			helper = helper.getNext();
		}
		
		// 同时移动first,helper m-1次
		while(true){
			// 圈中只有一个人
			if(first == helper){
				break;
			}
			
			for(int j=0;j<countNum-1;j++){
				first = first.getNext();
				helper = helper.getNext();
			}
			
			System.out.printf("小孩%d出圈!",first.getNo());
			// 让first指向的小孩节点出圈
			first = first.getNext();
			helper.setNext(first);
		}
		System.out.printf("最后的小孩%d出圈!",first.getNo());
	}
}

class BoyNode{
	private int no;
	private BoyNode next;
	
	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public BoyNode getNext() {
		return next;
	}

	public void setNext(BoyNode next) {
		this.next = next;
	}

	public BoyNode(int no){
		this.no = no;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值