展开全部
非递归的
#include <iostream>
char *reverse_string(char *str){
// 判断字符是否为null或是空字符串
if (NULL == str || '\0'==str ) {
return str;
}
// 定义char数组指针
char *start = str;
char *end = str;
while(*end!='\0'){//指向最后一个结点
end++;
}
// 交换头和尾的值
char temp;
--end;// 去除\0的位置
while (start < end){
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
return str;
}
int main(int argc, char* argv[])
{
// suppress warnings
(void)argc; (void)argv;
char ss[6] = {0};
sprintf(ss, "abcdefg");
char *ss_rev = reverse_string(ss);
printf("ss_rev =%s\n", ss_rev);
return 0;
}
递归的
#include <string.h>
#include <stdio.h>
#include <string>
char* reverse_string(char * string)
{
if (NULL == string) {
return string;
}
int len = strlen(string);
if (len <= 1) {
return string;
}
char tmp = *string;
char *str1 = reverse_string(string + 1);
for (int i = 0; i < len - 1; ++i) {
string[i] = string[ i + 1];
}
string[len - 1] = tmp;
return string;
}
int main(int argc, char* argv[])
{
// suppress warnings
(void)argc; (void)argv;
char ss[6] = {0};
sprintf(ss, "abcdefg");
char *ss_rev = (char *)reverse_string(ss);
printf("ss_rev =%s\n", ss_rev);
return 0;
}
请采纳,谢谢!
#include <iostream>
char *reverse_string(char *str){
// 判断字符是否为null或是空字符串
if (NULL == str || '\0'==str ) {
return str;
}
// 定义char数组指针
char *start = str;
char *end = str;
while(*end!='\0'){//指向最后一个结点
end++;
}
// 交换头和尾的值
char temp;
--end;// 去除\0的位置
while (start < end){
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
return str;
}
int main(int argc, char* argv[])
{
// suppress warnings
(void)argc; (void)argv;
char ss[6] = {0};
sprintf(ss, "abcdefg");
char *ss_rev = reverse_string(ss);
printf("ss_rev =%s\n", ss_rev);
return 0;
}
递归的
#include <string.h>
#include <stdio.h>
#include <string>
char* reverse_string(char * string)
{
if (NULL == string) {
return string;
}
int len = strlen(string);
if (len <= 1) {
return string;
}
char tmp = *string;
char *str1 = reverse_string(string + 1);
for (int i = 0; i < len - 1; ++i) {
string[i] = string[ i + 1];
}
string[len - 1] = tmp;
return string;
}
int main(int argc, char* argv[])
{
// suppress warnings
(void)argc; (void)argv;
char ss[6] = {0};
sprintf(ss, "abcdefg");
char *ss_rev = (char *)reverse_string(ss);
printf("ss_rev =%s\n", ss_rev);
return 0;
}
请采纳,谢谢!
更多追问追答
追问
如果是用递归实现呢
追答
递归的例子追加了,请采纳
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询