约瑟夫环问题题解
按照1-8順尋存儲,起始位置為3,數到4的人出列。
?
#include<iostream> using namespace std; typedef struct node {int num;struct node* next; }Node; int main() {int n = 8, k = 3, m = 4;Node*h = (Node*)malloc(sizeof(Node));h->num = 1;h->next = NULL;Node*p = NULL; ? ?//存儲臨時結點Node*q = h; ? //q負責串連結點組成鏈表int i;for (i = 2; i <= 8; i++){p = (Node*)malloc(sizeof(Node));p->num = i;p->next = NULL;q->next = p; ?//存儲新生成的結點q = q->next; ? //當前存儲結點后移,最后一個的q next始終為空}q->next = h;//定位初始位置for (i = 1; i < k; i++){h = h->next;}while(h->next!=h){//要刪除結點的前一個結點for (i = 1; i < m - 1; i++){h = h->next;}p = h->next;cout << p->num << endl;h->next = p->next;free(p);h = h->next;//因為刪除了一個所以要繼續向下走一個}cout << p->num << endl; //最后一個結點free(h);system("pause");return 0; }?
總結
- 上一篇: 励志网名男生127个
- 下一篇: 数组中一个属出现奇数次,其他数都出现偶数