18.n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,

题目: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 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值