输入一行字符反向输出

/*
题目描述:
输入一行字符(可包含空格)
将其反向输出

示例:
输入:
hello world

输出:
dlrow olleh
*/
#include <iostream>
#include <stack> // support for stack template class
using namespace std;

//方法一:栈方法
void print_Inverse_Using_Stack(char *s)
{
	stack<char> ss;
	for(int i = 0; i < strlen(s); i++)
	{
		ss.push(s[i]);
	}
	while(!ss.empty())
	{
		cout<<ss.top();
		ss.pop();//注意top不会进行出栈操作,所以需手动pop
	}
}

//方法二:递归方法
void print_Inverse_Using_Recusive(char *s, int i)
{
	if(i == strlen(s))
		return;
	i++;
	print_Inverse_Using_Recusive(s, i);
	cout<<s[--i];
}

int main()
{
	//对于char* / char[]
	char s[1001];
	cout<<"Please input char[]:"<<endl;
	cin.getline(s, 1000);//iostream下的函数, 第二个参数表示允许的最大输入长度
	print_Inverse_Using_Recusive(s,0);
	cout<<endl;

	return 0;
}

这题需要掌握三点:

1.如何读取一行字符串输入(包括空格),见C++读取一行字符串输入

2.STL栈的使用,最常用的是top(),pop(),empty()三个函数

3.递归的思想及其应用


这题解法其实跟我的另一篇博客解题思想差不多:

链表反向输出实例

反倒链表反转稍微处理得还复杂些。



posted @ 2016-09-24 00:06  Victor_Lv  阅读(589)  评论(0编辑  收藏  举报