1. 程式人生 > 實用技巧 >用迴圈連結串列實現約瑟夫環

用迴圈連結串列實現約瑟夫環

約瑟夫問題:

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    int data;
    struct node * next;
}node;
//建立一個有n個結點的迴圈連結串列
node * initLink(int n){
    node * head=(node*)malloc(sizeof(node));
    node * temp=head;
    for (int i=1; i<=n; i++) {
        node * p=(node*)malloc(sizeof
(node)); p->data=i; p->next=NULL; temp->next=p; temp=p; } temp->next=head->next;//首尾相連,組成迴圈連結串列,去掉了頭結點head free(head); return temp->next; } void find(node * head,int m){ node * temp; node * p=head; while (p->next!=p) {
//找到從報數1開始,報m的人 for (int i=1; i<m-1; i++) { p=p->next; } //此時p是要刪除的結點的前一個結點 temp = p->next; p->next=temp->next; p = p->next;//繼續使用p指標指向出列編號的下一個編號,遊戲繼續 printf("出列人的編號為:%d\n",temp->data); free(temp); } printf(
"出列人的編號為:%d\n",p->data); } int main() { int n,m; printf("輸入圓桌上的人數n:"); scanf("%d",&n); node* head=initLink(n); printf("數到m的人出列:"); scanf("%d",&m); find(head, m); return 0; }