首页 > 编程语言 > 详细

C/C++,数据结构单链表实现约瑟夫环

时间:2016-01-05 01:35:07      阅读:291      评论:0      收藏:0      [点我收藏+]

约瑟夫环——围成一圈,定义一个数值K,从任意位置开始计数,每走K步删除当前位置结点,直到剩下最后一个结点,求最后一个结点


//单链表结构以及Find函数参见 2016-1-2 13:56 发表博客

SListNode* Joseph(SListNode *&pos, int K) //约瑟夫环
{
 assert(pos);
 if (K > 0)
 {
  SListNode *tmp = pos;
  while (1)
  {
   int count = K;
   while (--count)
   {
    tmp = tmp->next;
   }
   if (tmp->next == tmp)
    return tmp;
   SListNode *cur = tmp->next;//删除tmp位置的结点,思路:pos与下一位置结点元素值进行交换后,删除下一结点
   DataType Tmpcount = cur->data;
   tmp->next = cur->next;
   cur->data = tmp->data;
   tmp->data = Tmpcount;
   free(cur);
  }
 }
 return NULL;
}

void Test7()// Joseph
{
 printf("//Test7() Joseph \n");
 SListNode *LL = NULL;
 PushBack(LL, 1);
 PushBack(LL, 2);
 PushBack(LL, 3);
 PushBack(LL, 4);
 PushBack(LL, 5);
 PushBack(LL, 6);
 PushBack(LL, 7);
 Find(LL, 7)->next = Find(LL, 1);
 printf("%d\n", Joseph(LL, 3)->data);
}


技术分享

C/C++,数据结构单链表实现约瑟夫环

原文:http://10739786.blog.51cto.com/10729786/1731557

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!