Java自创链表实现约瑟夫杀人环

约瑟夫杀人环想必大家都已经有所了解,一共n个人坐成一圈,从第一个人开始报数(从1开始),若报到m则此人出列,下一个人重新开始报数,一次往复,直至所有人都出列。
在之前,已经用C语言的链表写过此类方法,但是在Java中怎么实现呢?下面是我的代码
自定义结点类

public class Node {
	int num;
	Node next;	
	public Node() {
		
	}	
	public Node(int num, Node next) {
		super();
		this.num = num;
		this.next = next;
	}		
}

约瑟夫主体

public class Joeph {
	Node first;		//头结点
	Node last;	//尾结点
	private int size; //链表长度
	
	public void add(int num) {	//增加元素
		Node temp = new Node();
		if(first == null) {
			temp.num = num;
			temp.next = first;
			first = temp;
			last = first;
		}else {
			temp.num = num;
			last.next = temp;
			temp.next = first;
			last = temp;
		}
		size++;
	}

	public int getSize() {	//获取链表长度
		return size;
	}
	
	public void remove(int index) {	//删除链表某位置元素
		Node temp = new Node();
		temp = first;
		int i = 1;
		if(index == 1) {		//判断头元素
			last.next = first.next;
			first = last.next;
		}else {
			while(i+1 < index) {
				temp = temp.next;
				i++;
			}
			if(i+1 == index) {
				System.out.print(temp.next.num + "   ");
				temp.next = temp.next.next;
				first = temp.next;
			}
		}
		size--;
	}
	
	public void bianli() {		//遍历链表
		Node temp = new Node();
		temp = first;
		while(temp.next!= first) {
			System.out.print(temp.num + "	");
			temp = temp.next;
		}		
		System.out.println(temp.num);
		
	}
}

主函数

	public static void main(String[] args) {
		Joeph a = new Joeph();
		int people,password;	//参与人数与密码(报到多少的人出列)
		Scanner sc = new Scanner(System.in);
		System.out.println("输入参与游戏人数:");
		people = sc.nextInt();
		for(int i = 1; i <= people;i++) {	//向链表中插入元素
			a.add(i);
		}
		System.out.println("输入密码:");
		password = sc.nextInt();
		while(a.getSize()!=0) {	//链表长度不为空时一直删除
			a.remove(password);
		}
		System.out.println();
		System.out.println("最后存活下来的是:" + a.first.num);
	}
	/**
	 * output:
	 * 输入参与游戏人数:
	 * 3
	 * 输入密码
	 * 3
	 * 3	1	2
	 * 最后存活下来的是:2
	 */
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值