题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,
每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。
当一个数字删除后,从被删除数字的下一个继续删除第m个数字。
求出在这个圆圈中剩下的最后一个数字。
July:我想,这个题目,不少人已经 见识过了。
这里创建一个链表,单循环,然后逐渐删除!
#include <iostream>
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
ListNode();
ListNode(int n);
};
void insert(ListNode** root,int n);
ListNode* find(ListNode* root,int n);
int main()
{
ListNode* root = NULL;
ListNode* temp = NULL;
insert(&root,1);
insert(&root,2);
insert(&root,3);
insert(&root,4);
insert(&root,5);
insert(&root,6);
insert(&root,7);
insert(&root,8);
int i = 3 ; //每次要删除的第刻个数
temp = find(root,3);
return 0;
}
void insert(ListNode** root,int n)
{
ListNode* temp = new ListNode(n) ;
temp->m_pNext = (*root) ;
(*root) = temp ;
}
ListNode::ListNode()
{
m_pNext = NULL ;
}
ListNode::ListNode(int n)
{
m_nKey = n ;
m_pNext = NULL ;
}
ListNode* find(ListNode* root,int n)
{
ListNode* head = root ;
ListNode* temp = root ;
ListNode* dele = NULL ;
while (temp->m_pNext != temp)
{
for (int i=0;i<n-2;i++)
{
if (temp->m_pNext == NULL)
temp->m_pNext = root ;
temp = temp->m_pNext ;
}
if (temp->m_pNext == NULL)
temp->m_pNext = root ;
dele = temp->m_pNext;
if (dele->m_pNext == NULL)
dele->m_pNext = root ;
temp->m_pNext = dele->m_pNext ;
temp = temp->m_pNext ;
delete dele ;
}
if (temp == root)
return temp->m_pNext ;
else return temp ;
}