约瑟夫问题

问题重述:9个小孩围坐在一圈,开始报数,数到三的退出,求最后赢的孩子?

解决方法:链表的定义;链表节点元素的删除等

package com.homework37;

public class Demo37 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Node n = new Node();
		n.createLink(9);
		n.show();
		n.startGame();
		n.show2();

	}

}

class Node

{
	int number;
	Node next;
	Node head;
	Node curr;
	int lens;

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public Node getNext() {
		return next;
	}

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

	public void createLink(int lens) {
		this.lens = lens;
		for (int i = 1; i <= lens; i++) {
			if (i == 1) {
				Node n = new Node();
				head = n;
				curr = n;
				curr.next = null;
				n.setNumber(i);

			} else if (i == lens) {
				Node n = new Node();
				n.setNumber(i);
				curr.next = n;
				curr = n;
				curr.next = head;
			} else {
				Node n = new Node();
				n.setNumber(i);
				curr.next = n;
				curr = n;
			}
		}
	}

	public void show() {

		curr = head;
		while (true) {
			System.out.println(curr.number + " ");
			if (curr.next == head) {
				break;
			}
			curr = curr.next;
		}
	}

	public void startGame() {
		curr = head;
		Node exit;
		while (true) {
			for (int i = 1; i <= 2; i++) {

				if (i == 2) {
					exit = curr.next;
					curr.next = curr.next.next;
				}
				curr = curr.next;
			}
			if(curr.next.next==curr)
			{
				break;
			}
		}
	}

	public void show2() {

		curr = head;
		while (true) {
			System.out.print(curr.number + " ");
			if (curr.next == head) {
				break;
			}
			curr = curr.next;
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值