typedef struct node1 {
int data;
struct node1 *next;
} node1_t, *link;
void monkey_test(void)
{
int m = 0;
int n = 0;
int j = 0;
int answner[16] = { 0 };
int count = 0;
link tail = NULL;
link p,q = NULL;
link head = (link)malloc(sizeof(node1_t));
if (head == NULL) {
printf("malloc fail\n");
return;
}
head->data = -1;
head->next = NULL;
while (1) {
printf("输入n,m:\n");
scanf("%d,%d", &n, &m);
if (0 == m || 0 == n) {
free(head);
break;
} else {
tail = head;
for(int i = 0; i < n; i++) {
link node = (link)malloc(sizeof(node1_t));
if (node == NULL) {
printf("malloc fail\n");
// 释放链表
return;
}
node->data = i + 1;
node->next = NULL;
printf("++%d++\n", node->data);
tail->next = node;
node->next = head->next;
tail = node;
}
p = head->next;
q = tail;
j = 1;
while (p != q) {
if (j == m) {
q->next = q->next->next;
free(p);
p = q->next;
j = 1;
} else {
q = p;
p = p->next;
j++;
}
}
answner[count++] = p->data;
free(p);
head->next = NULL;
}
}
for(int k = 0; k < 16; k++) {
printf("answer[%d] = %d\n", k, answner[k]);
}
return;
}
``
约瑟夫环实现
最新推荐文章于 2024-09-02 16:35:28 发布