By
yusijia
Updated:
循环链表
- 用一道经典例题来理解吧!
- 约瑟夫环问题
- 补:约瑟夫环问题其实还可以用数论的知识解。
题目:
有n个人(n不是特别大的数),排成一个圈,从第一个人开始数1,数到m的人出队,然后第m+1个人数1… 一直这样循环下去,求最后的一个幸存的人是谁

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include<stdio.h> #include<stdlib.h> struct node{ int v; struct node *next; }*head; void insert_node(int val) { struct node *p=(struct node*)malloc(sizeof(struct node)); p->v=val; p->next=head; head=p; } void delete_node(struct node *p) { struct node *q=p->next; p->v=p->next->v; p->next=q->next; free(q); } int main() { int n,m,i; struct node *p; while(scanf("%d%d",&n,&m)==2 && n) { head=NULL; for(i=n;i>0;i--) insert_node(i); p=head; while(p->next!=NULL) p=p->next; p->next=head; p=p->next; while(--n) { for(i=1;i<=m-1;i++) p=p->next; delete_node(p); } printf("%d\n",p->v); free(p); } return 0; }
#include<stdio.h> #include<stdlib.h> struct node{ int v; struct node *next; }*head; void insert_node(int val) { struct node *p=(struct node*)malloc(sizeof(struct node)); p->v=val; p->next=head; head=p; } void delete_node(struct node *p) { struct node *q=p->next; p->v=p->next->v; p->next=q->next; free(q); } int main() { int n,m,i; struct node *p; while(scanf("%d%d",&n,&m)==2&&n) { head=NULL; for(i=n;i>=0;i--) insert_node(i); p=head; while(p->next!=NULL) p=p->next; p->next=head; p=p->next; while(n--) { for(i=1;i<=m-1;i++) p=p->next; delete_node(p); } printf("%d\n",p->v); free(p); } return 0; }
|