约瑟夫问题

来源:互联网 发布:大数据时代的阅读答案 编辑:程序博客网 时间:2024/06/11 08:11

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

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

package com.homework37;public class Demo37 {public static void main(String[] args) {// TODO Auto-generated method stubNode 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 0