《程序员面试宝典》--约瑟夫环

  • malloc函数使用方法:
 char * buffer;
 printf ("How long do you want the string? ");
 scanf ("%d", &i);
 buffer = (char*) malloc (i+1);
  • 约瑟夫环编程实现
     1 /* C编程实现约瑟夫环,还有一种数学递归推到方法.用户输入M,N值,
     2 从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出。
     3 写出C程序。(约瑟夫环问题 Josephus)*/
     4 
     5 #include <stdio.h>
     6 #include <stdlib.h>
     7 #define OK 1
     8 #define ERROR 0
     9 
    10 //链表节点
    11 typedef struct Node
    12 {
    13     int  pos;
    14     struct Node *next;
    15 }Node,*pNode;
    16 
    17 //创建循环链表,注意:head节点不能在子函数中赋值,否则程序不报错但是无法运行
    18 //赋值语句是指 head=cur,head=(pNode)malloc(sizeof(Node)),只要出现等号就不行
    19 void CreatRing(pNode head,int m)
    20 {
    21     int i=1;
    22     pNode cur=NULL,pre=NULL;
    23     cur = head;
    24     pre = head;
    25     while(--m>0)
    26     {
    27   pre = cur;
    28         cur->next=(pNode)malloc(sizeof(Node));
    29         cur=cur->next;
    30         cur->next=NULL;
    31         cur->pos=++i;
    32         pre->next=cur;
    33     }
    34     cur->next = head;
    35 }
    36 
    37 void KickFromRing(pNode head,int m)
    38 {
    39     int i,j;
    40     pNode cur = NULL, pre = NULL;
    41     cur = head;
    42     while(cur->next != NULL)
    43     {
    44         for(i=1;i < m;i++)
    45         {
    46             pre = cur;
    47             cur = cur->next;
    48         }
    49         j = cur->pos;
    50         printf("pop %d \n",j);
    51         pre->next = cur->next;
    52         free(cur);
    53         cur = pre->next;
    54         //必须加if,最后一个元素弹出后,由于上次循环中cur=pre,
    55         //cur->next != NULL成立,程序会继续运行
    56         if(cur->next == cur) 
    57         {
    58             j = cur->pos;
    59             printf("pop %d \n",j);
    60             break;
    61         }
    62     
    63     }
    64 }
    65 
    66 int main()
    67 {
    68     int i,m,n;
    69     printf("Input m= ,n= \n");
    70     scanf("%d %d",&m,&n);
    71     if(m<1 || n<1)
    72     {
    73         printf("error input! \n");
    74         system("pause");
    75         return 0;
    76     }
    77     pNode head=NULL,p=NULL;
    78     head = (pNode)malloc(sizeof(Node));
    79     head->next=NULL;
    80     head->pos = 1;
    81     CreatRing(head,n);
    82     p=head;
    83     for(i=1;i<=n;i++)
    84     {
    85         printf(" 第%d个元素是%d \n",i,p->pos);
    86         p=p->next;
    87     }
    88     KickFromRing(head,m);
    89     return 0;
    90 }

     

posted @ 2015-08-03 16:39  Richard_Meng  阅读(199)  评论(0)    收藏  举报