约瑟夫环,100个人围成圈圈,逢3退出,求最后剩下的人的编号(分别用数组和双向循环链表实现)

>>双向循环链表

#include <stdio.h>

#include <stdlib.h>

typedef struct node
{
int data;
struct node *front;
struct node *next;
}list_t;

//添加100个节点
list_t *add_people(list_t *head, int data)
{
if(1 == data)
{
head = malloc(sizeof(list_t));
head->data = data;
head->front = head;
head->next = head;
return head;
}
else
{
list_t *newnode = malloc(sizeof(list_t));
newnode->data = data;
newnode->next = head->next;
newnode->front = head;
newnode->front->next = newnode;
newnode->next->front = newnode;
return NULL;
}
}

int out_list(list_t *head)
{
int left = 100; //剩余人数
while(left != 1)
{
list_t *tmp = head->next->next; //3的位置
printf("%d\n", tmp->data); //打印退出的人员编号
tmp->front->next = tmp->next;
tmp->next->front = tmp->front; //删除节点
free(tmp); //释放空间
head = head->next->next; //重新从1开始计数
left--; //人数减1
}
printf("最后的人的位置%d\n", head->data);
return 0;
}

int main(int argc, const char *argv[])
{
int i = 0;
list_t *head = NULL; 
head = add_people(head, 1);
for(i = 100; i > 1; i--)
{
add_people(head, i);
}

out_list(head);
return 0;

}

通过运行代码

3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 2 7 11 16 20 25 29 34 38 43 47 52 56 61 65 70 74 79 83 88 92 97 1 8 14 22 28 35 41 49 55 62 68 76 82 89 95 4 13 23 32 44 53 64 73 85 94 5 19 37 50 67 80 98 17 40 59 86 10 46 77 26 71 31 100 58 最后的人的位置是91


>> 数组

#include <stdio.h>


int out_array(int data[], int num)
{
int i = 0;
int count = 0;
int left = 100;
while(left != 1)
{
count++;
i++;
if(data[i-1] == 0)
{
count--;
}
if(3 == count)
{
printf("%d ", data[i-1]);
data[i-1] = 0;
count = 0;
left--;
}
if(100 == i)
{
i = 0;
}
}


for(i = 0; i < 100; i++)
{
if(data[i] > 0)
{
printf("最后的人的位置是%d\n", data[i]);
}
}

return 0;
}


int main(int argc, const char *argv[])
{
int i = 0;
int data[100];
for(i = 0; i < 100; i++)
{
data[i] = i+1;
}

out_array(data, 100);
return 0;

}


通过运行代码

3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 2 7 11 16 20 25 29 34 38 43 47 52 56 61 65 70 74 79 83 88 92 97 1 8 14 22 28 35 41 49 55 62 68 76 82 89 95 4 13 23 32 44 53 64 73 85 94 5 19 37 50 67 80 98 17 40 59 86 10 46 77 26 71 31 100 58 最后的人的位置是91


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值