循环法的代码量极为简单,递归法也简单,循环链表的代码量就很大了
Java有ArrayList可以很方便的做这道题,但还未尝试,日后补充。
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include <iostream> #include <stdio.h> #include <stdlib.h>
using namespace std;
void LinkedList(int amount,int count) { struct Node { int number; struct Node * next; }; Node *head = (Node *)malloc(sizeof(Node)); Node *s = (Node *)malloc(sizeof(Node)); Node *temp; s = head; for(int i=1; i<=amount; ++i) { if(i == 1) { s->number = i; continue; } temp = (Node *)malloc(sizeof(Node)); temp->number = i; s->next = temp; s = temp; } temp->next = head;
Node *kill = temp; Node *q; for(int i=0;i<amount;++i) { for(int j=0;j<count;++j) { temp = kill; kill = kill->next; } cout<<kill->number<<" "; q = kill; temp->next = kill->next; kill = temp; delete q; }
}
int Joseph(int amount,int count) { if(amount == 1) return 0; else return (Joseph(amount-1,count)+count)%amount; }
int Joseph_Step(int amount,int count,int i) { if(i == 1) return (amount+count-1)%amount; else return (Joseph_Step(amount-1,count,i-1)+count)%amount; }
int Loop(int amount,int count) { int result = 0; for(int i=2 ; i<=amount ; ++i) { result = (result + count)%i; } return result; }
int main() { int amount,count; cout<<"请输入人数(大于1):"; cin>>amount; cout<<"出列序号为:"; cin>>count;
cout<<"循环所得结果为:"; cout<<Loop(amount,count)+1<<endl;
cout<<"递归所得结果为:"; cout<<Joseph(amount,count)+1<<endl;
cout<<"递归算法所得队列为:"; for(int i = 1; i <= amount; ++i) cout<<Joseph_Step(amount,count,i)+1<<" "; cout<<endl;
cout<<"循环链表所得队列为:"; LinkedList(amount,count);
return 0; }
|