问题描述:
N个人围成一圈,从第一个开始报数,第M个将被杀掉,最后剩下一个,其余人都将被杀掉。例如N=6,M=5,被杀掉的顺序是:5,4,6,2,3,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 #include <iostream> using std::cout;using std::cin;using std::endl;struct Node { int data; Node* pred; Node* succ; }; Node* rear; Node* head; int count = 0 ; void InitLinkedList (int ) ; void DeleteNode (Node*) ; int main () { cout << "请输入总人数n,开始计数的人k(1为起点),被杀掉的次序m:" ; int n, k, m; cin >> n >> k >> m; if (n <= k || n <= m) abort (); cout << "被杀的次序为:" ; InitLinkedList (n); Node* ptr = head; while (--k) ptr = ptr->succ; while (count) { int i = m; while (--i) ptr = ptr->succ; cout << ptr->data << ' ' ; Node* tmp = ptr; ptr = ptr->succ; DeleteNode (tmp); } } void InitLinkedList (int n) { if (n <= 0 ) return ; head = new Node; head->succ = head; head->pred = head; head->data = 1 ; rear = head; count++; for (int i = 2 ; i <= n; i++) { Node* ptr = new Node; ptr->data = i; ptr->succ = rear->succ; ptr->pred = rear; rear->succ = ptr; ptr->succ->pred = ptr; rear = ptr; count++; } } void DeleteNode (Node* p) { if (p == head) { head = head->succ; rear->succ = head; head->pred = rear; delete p; count--; } else if (p == rear) { rear = rear->pred; rear->succ = head; head->pred = rear; delete p; count--; } else { p->pred->succ = p->succ; p->succ->pred = p->pred; delete p; count--; } }