单循环链表解决约瑟夫问题

#include <iostream>
using namespace std;
typedef int Elemtype;
typedef struct ListNode
{
	Elemtype data;
	ListNode *next;
}ListNode;

ListNode* CreateList(ListNode *&first,int n)
{
	ListNode *last=new ListNode;
	int i;
	last=first;
	first->next=last;
	last->next=first;
	last=first;
	Elemtype temp;
	for(i=0;i<n;++i)
	{
		temp=i+1;
		ListNode *newnode=new ListNode;
		newnode->data=temp;
		newnode->next=NULL;
		newnode->next=last->next;
		last->next=newnode;
		last=newnode;
	}
	return first;
}

void Delete(ListNode *&first,int n,int m)           //n表示次数,m表示编号
{
	int i,j;
	ListNode *head=new ListNode;
	ListNode *current=new ListNode;
	ListNode *pre=new ListNode;
	ListNode *temp=new ListNode;
	head=first;
	pre=first;
	current=pre->next;
	for(i=0;i<n;++i)
	{
		for(j=0;j<m-1;++j)
		{
			if(current->next==head)
				current=current->next;
			pre=current;
			current=current->next;
		}
		pre->next=current->next;
		temp=current;
		cout<<"出列的人编号:"<<temp->data<<endl;
		current=current->next;
		if(current==head)
			current=current->next;
		delete temp;
	}
}

void Display(ListNode *first)
{
	ListNode *current;
	current=first->next;
	while (current!=first)
	{
		cout<<current->data<<" ";
		current=current->next;
	}
}

int main()
{
	ListNode *first=new ListNode;
	first->next=NULL;
	int i,n,m;
	cout<<"约瑟夫问题测试"<<endl; 
	cout<<"请输入人数的总数"<<endl;
	cin>>i;
	first=CreateList(first,i);
	cout<<"请输入循环次数和以几为一次循环的号码"<<endl; 
	cin>>n>>m;
	Delete(first,n,m);
	cout<<"剩下的人编号分别是:"<<endl;
	Display(first);
	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值