1、遞歸調用方式實現無符號數反向輸出
C語言實現(DEV c++4.9.9.2運行通過)
[cpp]
#include<stdio.h>
void reverse_print(unsigned long num)
{
if(num==0)
return;
printf("%d",num%10); //輸出最低位
reverse_print(num/10);//遞歸調用,依次輸出最低位
}
int main(void)
{
unsigned long num=12345678;
reverse_print(num);
printf("\n");
system("PAUSE");
return 0;
}
#include<stdio.h>
void reverse_print(unsigned long num)
{
if(num==0)
return;
printf("%d",num%10); //輸出最低位
reverse_print(num/10);//遞歸調用,依次輸出最低位
}
int main(void)
{
unsigned long num=12345678;
reverse_print(num);
printf("\n");
system("PAUSE");
return 0;
}
2、棧實現字符串的反轉
C++實現,用C語言實現需要自己定義棧(DEV c++4.9.9.2運行通過)
[cpp]
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<char> s;
char n;
cout<<"輸入需要反轉的字符串:"<<endl;
n=getchar();
while(n!='\n')
{
s.push(n);
n=getchar();
}
while(!s.empty())
{
cout<<s.top();
s.pop();
}
cout<<endl;
system("pause");
return 0;
}
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<char> s;
char n;
cout<<"輸入需要反轉的字符串:"<<endl;
n=getchar();
while(n!='\n')
{
s.push(n);
n=getchar();
}
while(!s.empty())
{
cout<<s.top();
s.pop();
}
cout<<endl;
system("pause");
return 0;
}
3、設立頭尾指針實現字符串反向輸出
C語言實現(DEV c++4.9.9.2運行通過)
[cpp]
#include<stdio.h>
char *converse(char *str);
int main(int argc,char *argv[])
{
char str[] = "1234567890zxcvbnma"; //需要轉換的字符串數組
char *sdest;
printf("before converse:str= %s \n",str);
sdest = converse(str);
printf("after converse:str= %s \n",sdest);
system("PAUSE");
return 0;
}
char *converse(char *str)
{
char temp;
char *s1 = str; //s1:頭指針
char *s2 = str+strlen(str)-1;//s2:尾指針
//頭指針和尾指針交換指向的值,並向中間移動,直到相遇
for(;s1 < s2;s1++,s2--)
{
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
return str;
}
#include<stdio.h>
char *converse(char *str);
int main(int argc,char *argv[])
{
char str[] = "1234567890zxcvbnma"; //需要轉換的字符串數組
char *sdest;
printf("before converse:str= %s \n",str);
sdest = converse(str);
printf("after converse:str= %s \n",sdest);
system("PAUSE");
return 0;
}
char *converse(char *str)
{
char temp;
char *s1 = str; //s1:頭指針
char *s2 = str+strlen(str)-1;//s2:尾指針
//頭指針和尾指針交換指向的值,並向中間移動,直到相遇
for(;s1 < s2;s1++,s2--)
{
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
return str;
}