Solving Josephus with linked lists

a 夏天 提交于 2019-12-04 22:08:17

I didn't read all the code above, I think it can find the last item for given N and M

According to the original problem, 12<N<100. So, probably it can be solved in the given time limit simply with brute force.

  • You read in N
  • start a loop for finding m from 1
  • in the loop:
    • run the algorithm, using the loop variable as m. If the last item is 13, return the loop variable.

EDIT: You don't have to work a lot. You just simply start a loop instead of reading M.

M=1;
while(1)
{
//your code goes here: 
//build up the linked list with N element
//eliminate the nodes, until only one remains
//instead of writing out the last number, you check it: if it equals 13 print M, if doesn't, increment `M` and continue the loop.
 if(p->player_id==13)
 {
   printf("The minimal M is: %d\n", M);
   break;
 }
 else
   M++;
}

If You want to do this for multiple N-s, You can put this loop into a function. In this case insted of printing M, the function should return it. The funny thing is: The linked list part is done by You. Maybe You should try simpler exercises first.

EDIT 2: HERE is my final answer, check the structure and the output, I hope it is understandable.

NOTE: I think if You really want to learn, You should do something like this instead of jumping in a not trivial problem:

  • understand pointers
  • understand structs
  • understand linked lists
  • implement insert/update/delete to the head/tail/certain position of a linked list
  • solve Josephus problem by Yourself in 10 minutes
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!