forked from zhuxinquan/Data-Structure-And-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
josephus_sort.c
66 lines (61 loc) · 1.33 KB
/
josephus_sort.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
/*************************************************************************
> File Name: josephus_sort.c
> Author: zhuxinquan
> Mail: [email protected]
> Created Time: 2015年09月21日 星期一 23时31分40秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * next;
}Node, * LinkList;
LinkList Creat_Link(int n)
{
int i = 1;
LinkList head;
Node * p, *t;
t = head = (LinkList)malloc(sizeof(Node));
while(i <= n)
{
p = (Node *)malloc(sizeof(Node));
p->data = i++;
p->next = NULL;
t->next = p;
t = p;
}
t->next = head->next;
return t;
}
void josephus(LinkList tail, int m)
{
int i;
Node * pdel;
Node * pcur = tail->next;
Node * pre = tail;
while(pcur != pcur->next)
{
for(i = 1; i < m; i++)
{
pre = pre->next;
}
pdel = pre->next;
pcur = pdel->next;
pre->next = pcur;
printf("%3d", pdel->data);
free(pdel);
}
printf("%3d", pcur->data);
free(pcur);
printf("\n");
}
int main(void)
{
int n, m;
LinkList tail;
printf("input n, m(eg: 7,3):");
scanf("%d,%d", &n, &m);
tail = Creat_Link(n);
josephus(tail, m);
return 0;
}