zoukankan      html  css  js  c++  java
  • 约瑟夫环问题(c语言) by链表

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 typedef struct person{
     5     int num;
     6     struct person* next;
     7 }P;
     8 int main()
     9 {
    10     int n,m;
    11     scanf("%d%d",&n,&m);
    12     P* ph=(P*)malloc(sizeof(P));//建个头(不存数据) 
    13     ph->next = NULL;
    14     P* a = ph;
    15     for(int i=0; i<n; i++)
    16     {
    17         P* p=(P*)malloc(sizeof(P));
    18         p->num = i+1;
    19         a->next = p;//连接 
    20         a = p;
    21         if(i!=n-1)
    22         {
    23             p->next = NULL;
    24         } else //使之成环 
    25         {
    26             p->next = ph->next;
    27         }            
    28     }
    29     a = ph->next;//从此处开始在环里转圈圈  O(∩_∩)O 
    30     
    31     int N=n, M=m,i=0;
    32     P* pre = NULL;
    33     while(N--)
    34     {
    35         if(M==1){
    36             M=m;//初始化 
    37         }
    38         while(M != 1)//每隔 m-1 个节点输出一下 
    39         {
    40             pre = a;//记住a停留过的上一个节点 
    41             a = a->next;
    42             M--;
    43         }
    44         printf("%d ",a->num);
    45         //把该节点从环中抛弃 
    46         a = a->next;
    47         pre->next = a;    
    48     }
    49     return 0;
    50 }
    51     
    天涯犹在,不诉薄凉。
  • 相关阅读:
    _proto_和prototype的区别
    ajax
    图片预加载
    loading动画
    WinSCP
    检测竖屏 横屏
    webstrom hbuilder快捷键
    vue 引入sass
    npm install -save 和 -save-dev 区别
    打乱数组顺序
  • 原文地址:https://www.cnblogs.com/Knight02/p/14587364.html
Copyright © 2011-2022 走看看