学习_指针操作解决约瑟夫出圈问题

来源:互联网 发布:华为手机mac地址查询 编辑:程序博客网 时间:2024/05/27 20:53

#include <stdio.h>

//解决思路:使用递归调用直至将字符串取完

void rouand(char *p_str,int n)  //该函数接收传递来的字符串首地址和按n取数
{
    if(!(*p_str))  //递归调用的终止条件
    {
        return;
    }
    int i = 0,j = 0,k = 0;
    char *q_str = p_str;

    //遍历字符串,将符合n的倍数的值取出
    for(;*(q_str);q_str++)
    {
        i++;
        if(!(i%n))
        {
            printf("%c ",*q_str);
            *q_str = '\0';   //取出该值将其置为'\0',在下面的语句将其移至字符串尾
        }
    }
    if(i < n) //当剩余字符串小于n的长度时,另作处理
    {
        q_str = p_str;
        int tmp = n%(i+1);
        printf("%c ",*(q_str+tmp));
        *(q_str+tmp) = '\0';
    }
    printf("\n");
    q_str = p_str;
    for(j = 0;j < i;j++)  //遍历替换好'\0'的字符串,将所有'\0'的字符移至最后,形成新的字符串
    {      //为熟悉指针操作才这样,使用数组更容易实现
        if(!(*(q_str+j)))
        {
            for(k = j;k < i-1;k++)
            {
                *(q_str+k) = *(q_str+k+1);
                *(q_str+k+1) = '\0';
            }
        }
    }
    printf("%s\n",p_str);

    rouand(p_str,n);   //递归调用,直至字符串取完
}

int main()
{
   // char str[100] = "abcdefghijklmnopqrst";
    char str[100] = "abcde";
    printf("%s\n",str);
    rouand(str,4);
    return 0;
}

 

0 0
原创粉丝点击