(数据结构习题)写一个递归算法实现字符串逆序存储,要求不另设串存储空间。

 写一个递归算法实现字符串逆序存储,要求不另设串存储空间。

#include<stdio.h>
#include<string.h>

void rev1(char *c);
void rev2(char *c);
void rev3(char *c);

int main(void)
{
    char str[]="abcde";
    printf("原字符串为 \n%s\n",str);
    int rev;
    printf("请输入要验证的方法(1-3):\n");
    scanf("%d",&rev);
    switch(rev)
    {
    case 1:
        rev1(str);
        printf("改变后的字符串为\n%s\n",str);
        break;
    case 2:
        rev2(str);
        printf("改变后的字符串为\n%s\n",str);
        break;
    case 3:
        rev3(str);
        printf("改变后的字符串为\n%s\n",str);
        break;
    default:
        printf("Error!");
    }

    return 0;
}

void rev1(char *ch)
/*利用
'\n'当做临时交换空间
*/
{
    int len =strlen(ch);
    for (int i = 0; i < (len-1)/ 2; i++)
    {
        ch[len]=ch[i];
        ch[i]=ch[len-1-i];
        ch[len-1-i]=ch[len];
    }
    ch[len]='\0';
}

void rev2(char *ch)
/*利用
a=a+b;
b=a-b;
a=a-b;
*/
{
    int len =strlen(ch);
    for (int i = 0; i < (len-1)/2; i++)
    {
        ch[i] = ch[i] + ch[(len-1) - i];
        ch[(len-1) - i]= ch[i]- ch[(len-1) - i];
        ch[i] = ch[i] - ch[(len-1) - i];
    }
}

void rev3(char *ch)
/*利用
a^=b;
b^=a;
a^=b;
*/
{
    int len =strlen(ch);
    for (int i = 0; i < (len-1)/ 2; i++)
    {

         ch[(len-1) - i] ^= ch[i];
         ch[i] ^= ch[(len-1) - i];
         ch[(len-1) - i] ^= ch[i];
    }
}
#include<stdio.h>
#include<string.h>
char s[100];
int len;
void reverse(int i,int j)
{
	if(i==len/2)
		return ;
	char temp;
	temp=s[i];
	s[i]=s[j];
	s[j]=temp;
	reverse(++i,--j);
}

int main()
{
        printf("请输入字符串:\n");
	scanf("%s",s);
	len=strlen(s);
	reverse(0,len-1);
	printf("\n");
	printf("改变后的字符串为:\n");
	printf("%s\n",s);
}

 

  • 10
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值