Joesph約瑟夫問題(java實現)

class Node {
int data;
Node next;

Node(int data) {
this.data = data;
next = null;
}
}


class LinkList {
Node first = null;

public LinkList(int n) {
Node tmp;

tmp = first;
for (int i = 1; i < n + 1; i++) {
Node node = new Node(i);

if (first == null)
first = node;
else 
tmp.next = node;

tmp = node;
}

tmp.next = first;
}
}


public class Joesph {
static int joesph(int people, int num) {
LinkList list = new LinkList(people);
int flag = 0;
Node node;

node = list.first;
while (people != 1) {
flag++;

if (flag == num - 1) {
node.next = node.next.next;
flag = 0;
people--;
}

node = node.next;
}

return node.data;
}

public static void main(String[] args) {
System.out.println(joesph(5, 3));
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章