java实现约瑟夫循环 约瑟夫环java链表
转载
鉴于毕设是关于算法的,我又是用Java实现的,所以开始学习Java实现的一些算法。
第一个就是约瑟夫环,因为以前学数据结构的时候用C写过。不知道自己当时太笨还是怎么着,写出来的代码一长串,怎么看怎么麻烦,Java的简单多了。
1.Java循环链表版的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| public class Josephus {
static class Node{
int val;
Node next;
Node(int v){
val=v;
}
}//成员类,代表节点,类似于数据结构中的结构体
public static void main(String[] args) {
int N=9;//这个表示总人数
int M=5;//数到几的人出列
Node t=new Node(1);//头节点单列出来,方便形成循环链表
Node x=t;
for(int i=2;i<=N;i++)x=(x.next=new Node(i));//建立单向链表
x.next=t;//最后一个节点的next指向第一个节点,形成循环链表
System.out.println("出圈的顺序为:");
while(x!=x.next){
for(int i=1;i<M;i++)
x=x.next;
//此时x是将出列的节点的前一个节点
System.out.print(x.next.val+" ");
x.next=x.next.next;
}
System.out.println();
System.out.println("Survivors is "+x.val);
}//end main
}
|
2.这个是当初用C写的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| #include ><stdio.h>
#define size 7
typedef struct node{
int data;
int pass;
struct node * next;
}node,*LinkNode;
void main()
{
LinkNode head,p,s,q,r;
int x,y,n,m,i;
head=(node *)malloc(sizeof(node));
p=head;
for(n=1;n<=size;n++) {
printf("\n the %d number is :",n);
scanf("%d",&x);
printf("\n the %d pass is :",n);
scanf("%d",&y);
s=(node *)malloc(sizeof(node));
s->data=x;
s->pass=y;
p->next=s;
p=s;
}
head=head->next;
p->next=head;
m=20;
q=p->next;
while(q->next->next!=q)
{
if(m==2){
r=q->next;
m=r->pass;
printf(" %d",r->data);
q->next=r->next;
q=q->next;
}
if(m==1){
r->next=q;
r->next=q->next;
m=q->pass;
printf(" %d",q->data);
q=r->next;
}
else{
for(i=1;i<=m-2;i++){
q=q->next;
}
r=q->next;
q->next=r->next;
m=r->pass;
printf(" %d",r->data);
q=q->next;
}
}
r=q->next;
if(m%2==0){
printf(" %d %d",r->data,q->data);
}
else {
printf(" %d %d",q->data,r->data);
}
}
|
3.今天还在网上看了一个更简单的,先保存起来,还需要进一步的研究。
| int fun(int n, int m)
{
int i, r = 0;
for (i = 2; i <= n; i++)
r = (r + m) % i;
return r+1;
}
|
4.还有一种是用数组实现的Java版的约瑟夫环,暂时还没太懂。
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。