#ifndef __LOOPLIST__H
#define __LOOPLIST__H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int datatype_t;
typedef struct node{
datatype_t data;
struct node *next;
}loopnode_t;
extern void insert_tail_looplist(loopnode_t *head, datatype_t data);
extern loopnode_t *create_node();
extern void Josephu(int n, int k, int m);
#endif
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
#include "looplist.h"
loopnode_t *create_node()
{
loopnode_t *temp = NULL;
temp = (loopnode_t *)malloc(sizeof(loopnode_t));
if(NULL == temp){
printf("malloc is failed\n");
return NULL;
}
memset(temp,0,sizeof(loopnode_t));
return temp;
}
void insert_tail_looplist(loopnode_t *head, datatype_t data)
{
loopnode_t *temp = create_node();
loopnode_t *p = head; //注释,从第一个元素head开始判断,如果.next的值不为NULL 就把下一个元素赋值给p p=p->next 继续循环,直到p为最后一个元素
while(p->next!=head)
{
p = p->next;
}
//找到最后一个元素后要注意,第一步一定是先往要插入的元素存原来位置的元素地址(虽然是NULL), temp->next = p->next
//第二步才是把要插入的元素地址存储到最后一个元素next上 p->next = temp;
temp->data = data;
temp->next = p->next;
p->next = temp;
}
void Josephu(int n, int k, int m)
{
loopnode_t *head = create_node();
loopnode_t *cur_node = NULL;
loopnode_t *target_node= NULL;
loopnode_t *pre_node = NULL;
int total = 0;
head->data = 1;
head->next = head;
cur_node = head;
total ++;
for(int i=2; i<n+1; i++){
insert_tail_looplist(head, i);
total ++;
}
for(int j=0; j<k-1; j++){
cur_node = cur_node->next;
}
printf("出列序列为:");
while(total!=0)
{
for(int s=0; s<m-1; s++){
pre_node = cur_node;
cur_node = cur_node->next;
}
target_node = cur_node;
pre_node->next = cur_node->next;
printf("%d ", target_node->data);
cur_node = cur_node->next;
free(target_node);
target_node = NULL;
total--;
}
printf("\n");
}
- 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
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
#include "looplist.h"
int main()
{
int n,k,m;
printf("请输入[成员数,开始序号,报名数]:\n");
scanf("%d%d%d",&n,&k,&m);
Josephu(n, k, m);
return 0;
}