【100题】第十八题(约瑟夫循环)

一,题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。当一个数字删除后,从被删除数字的下一个继续删除第m个数字。求出在这个圆圈中剩下的最后一个数字。

二,思路:创建一个循环链表,每次走m步删除一个节点,最后剩下一个

三,源码:

#include <iostream> #include "malloc.h" using namespace std; struct node { int data; node *next; }; node *createList(int a[],int n) { node *head; node *p,*q; head=(node *)malloc(sizeof(node)); head->data=0; head->next=NULL; for(int i=0;i<n;i++) { p=(node *)malloc(sizeof(node)); p->data=a[i]; p->next=NULL; p->next=head->next; head->next=p; } q=head; while(q->next!=NULL) q=q->next; q->next=head; return head; } void display(node *head) { node *p; p=head; cout<<p->data<<endl; while(p->next!=head) { p=p->next; cout<<p->data<<endl; } } void deleteNode(node *head,int m) { node *p,*q; p=head; while(p->next!=head)//p为head前一个节点 p=p->next; while(p->next!=p) { q=p->next; for(int i=1;i<m;i++)//走几步 { p=q; q=q->next; } p->next=q->next;//删除节点 cout<<"delete node is:"<<q->data<<endl; } cout<<"last node is:"<<p->data<<endl; } int main() { int a[10]={1,2,3,4,5,6,7,8,9}; node *head; head=createList(a,9); display(head); //cout<<head->data; deleteNode(head,2); return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值