循环链表--解决Josephus问题
合集下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用循环链表解决:
1. #include <iostream> 2. usingnamespace 3. typedefstruct 4. data; 5. struct Node *next; 6. }Node,*List; 7. List Creatlist( 8. List head,p; 9. head=(Node*)malloc(sizeof(Node));
19. return head;
20. Output(List head)ut<<p->data<<
23. p=p->next;
24. }while(p!=head);
25. cout<<endl;
26. Play(List head,//第一种方法
27. List p,q;
37. cout<<endl;
38. Josephus(List h,//第二种方法
39. Node* p=h,*pre=NULL;
40. (i=0;i<n-1;++i)
41. (j=1;j<m;++j)
42.
pre=p;
43.
p=p->next;
44. cout<<"出列的人是 "<<p->data<<endl;
28. p=head; c=1; k=n;
29. while(k>1)
30. (c==m-1)
31.
q=p->next; p->next=q->next;
32.
cout<<q->data<<
33.
free(q);
34.
c=0; --k;
35. {c++; p=p->next;}
36. cout<<"The winner is "<<p->data;
cout<<"memory allocation error!\n"; exit(1); } head->data=1; head->next=head; for(i=n;i>1;--i) { p=(Node*)malloc(sizeof(Node)); if(!p) {
cout<<"memory allocation error!\n"; exit(1); } p->data=i; p->next=head->next; head->next=p; } return head; }
/luxiaoxun/article/details/7433024
1/5
2016/11/14
循环链表--解决Josephus问题 - luxiaoxun的专栏 - 博客频道 -
10. (!head)
11. cout<<"memory allocation error!\n"
2/5
2016/11/14
struct Node *next; }Node,*List;
循环链表--解决Josephus问题 - luxiaoxun的专栏 - 博客频道 -
List Creatlist(int n) {
List head,p; int i; head=(Node*)malloc(sizeof(Node)); if(!head) {
12. exit(1);
13. head->data=1; head->next=head;
14. (i=n;i>1;--i)
15. p=(Node*)malloc(sizeof(Node));
16.
cout<<"memory allocation error!\n"
17.
exit(1);
18. p->data=i; p->next=head->next; head->next=p;
2016/11/14
循环链表--解决Josephus问题 - luxiaoxun的专栏 - 博客频道 -
循环链表--解决Josephus问题
版权声明:本文为博主原创文章,未经博主允许不得转载。
单向循环链表:
空表:L->next = L。
与单链表的联系:判断表尾的方法不同:单链表用p==NULL;循环链表用p==L。
45. pre->next=p->next; free(p);
46. p=pre->next;
47. cout<<"The winner is "<<p->data<<endl;
48. main()
49. List head;
50. cout<<"Input the n and m :"
51. cin>>n>>m;
双向循环链表:一个结点包含指向后继(next) 和指向前驱(prior) 两个指针,两个方向又分别构成循环链表。
双向循环链表的插入和删除:
1.p之后插入s s->next = p->next; p->next = s; s->prior = p; s->next->prior = s;
2.p之前插入s s->prior= p->prior; p->prior = s; s->next = p; s->prior->next = s;
52. head=Creatlist(n);
53. Output(head);
54. Josephus(head,n,m);
55. return
#include <iostream> using namespace std;
typedef struct Node {
int data;
/luxiaoxun/article/details/7433024
3.删除p之后继s s = p->next; p->next = s->next; p->next->prior = p;
4.删除p p->prior->next= p->next; p->next->prior= p->prior;
循环链表--解决Josephus问题 题目:n个人围成一圈,从第一个开始顺序报数1,2,3.凡是报到3 者退出圈子,最后剩下的就是胜利者
void Output(List head) {
List p=head; do {
cout<<p->data<<" "; p=p->next; }while(p!=head); cout<<endl; }
voidPlay(Listhead,intn,intm)//第一种方法 {