1. 程式人生 > 其它 >迴圈連結串列求解約瑟夫問題 C語言

迴圈連結串列求解約瑟夫問題 C語言

技術標籤:資料結構連結串列c語言

#include<stdio.h>
#include "stdlib.h"
struct Node
{
    int data;
    struct Node *next;
};//建立一個結點結構體
 
int main()
{
    struct Node *head = NULL, *s, *q = NULL, *t;
    int n, m, count=0, i;
    printf("輸入總人數 m:\n");
    scanf("%d",&m);
    printf
("\n"); printf("輸入報到第幾個出列 n:\n"); scanf("%d",&n); for(i=0; i<m; i++) { s=(struct Node *)malloc(sizeof(struct Node)); s->data=i+1; s->next=NULL; if(i==0) { head=s; q=head; }
else { q->next=s; q=q->next; } }//建立一個不帶頭結點的單鏈表 q->next=head;//將單鏈表組成環狀,形成迴圈單鏈表 printf("\n"); printf("之前的序列為:\n"); q=head; while(q->next!=head) { printf("%d ",q->data); q=
q->next; }//依次輸出結點的值 printf("%d ",q->data); q=head; printf("\n"); printf("\n"); printf("依次出列的順序是:\n"); do { count++;//計數器開始計數 if(count==n-1) { t=q->next; q->next=t->next;//到n前面那個節點停止,然後刪除第n個節點 count=0;//計數器復位 printf("%d ", t->data);//輸出被淘汰的號碼 free(t);//釋放記憶體,防止記憶體洩露 } q=q->next; } while(q->next!=q); printf("\n"); printf("\n"); printf("最後剩下的人是: %d\n",q->data); }