循環鏈表創建約瑟夫環

循環鏈表創建約瑟夫環

【這是靚仔呀呀呀呀呀呀】
ps:此博客是copy的,但是對原博主的代碼進行了修改,原博主代碼有些無用代碼。以下是【這是靚仔呀】修改後的代碼。

#include <stdio.h>
#include <stdlib.h>
//單鏈表每個結點的創建 
typedef struct node{
    int number;
    struct node * next;
}person;
person * initLink(int n){
	//創建頭結點 
    person * head=(person*)malloc(sizeof(person));
    head->number=1;
    head->next=NULL;
    //cyclic用於備用 
    person * cyclic=head;
    //這是尾插法創建剩下的結點 
    for (int i=2; i<=n; i++) {
         person * body=(person*)malloc(sizeof(person));
        body->number=i;
        body->next=NULL; 
        cyclic->next=body;
        cyclic=cyclic->next;
    }
    
	//首尾相連
    cyclic->next=head;
    //返回這個循環鏈表的頭結點 
    return head;
}
void findAndKillK(person * head,int k,int m)
{
    person * tail=NULL;
    //找到編號爲k的人
    person * p=head;
    //指針移動k-1次 
    while (p->number!=k) {
        tail=p;
        p=p->next;
    }
    //從編號爲k的人開始,只有符合p->next==p時,說明鏈表只剩下一個結點 
    while (p->next!=p) {
        //找到從p報數1開始,報m的人,並且還要知道數m-1de人的位置tail,方便做刪除操作。
        for (int i=1; i<m; i++) {
            tail=p;
            p=p->next;
        }
        tail->next=p->next;//從鏈表上將p結點摘下來
        printf("出列人的編號爲:%d\n",p->number);
        free(p);
        p=tail->next;//繼續使用p指針指向出列編號的下一個編號,遊戲繼續
    }
    //用於輸出最後一個結點的值大小 
    printf("出列人的編號爲:%d\n",p->number);
    free(p);//釋放最後一個節點 
}
int main() {
    printf("輸入圓桌上的人數n:");
    int n;
    scanf("%d",&n);
    person * head=initLink(n);
    printf("從第k人開始報數(k>1且k<%d):",n);
    int k;
    scanf("%d",&k);
    printf("數到m的人出列:");
    int m;
    scanf("%d",&m);
    findAndKillK(head, k, m);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章