都是上面那个编程作业 我的思路是用栈进行逆序执行 然后就能不用递归做出来了
#include<iostream>
#include<stack>#include<string>
#include<cctype>
#include<sstream>
#include <strstream>
#define l_num 22
using namespace std;
bool isNum(string str)
{
string num = "1234567890";
if (str.find_first_not_of(num) == string::npos)
return true;
return false;
}
string inttow(int n) {
string str = "";
while (n)
{
string temp(1, n % 10 + '0');
str = temp + str;
n -= n % 10;
n =int(n/10.0);
}
return str;
}
int main()
{
int num;
int i;
cin >> num;
string s[20];//本来是动态分配的
string s1;
int n, x;
string b;
for (i = 0; i < num; i++)
{
cin >> s[i];
}
do
{
cin >> b;
if (b == "over") { break; }
else
{//如果没有结束
string a[l_num];
a[0] = b;
i = 1;
if (a[0] == "printall")
{
int cal;
for (cal = 0; cal < num; cal++)
{
cout << s[cal];
cout << endl;
}
}
else
{
do
{
cin >> a[i];
i++;
} while (getchar()!='\n');
stack<int> st;
stack<string> ss;
for (i--; i >= 0; i--)
{
int temp;
if (isdigit(a[i][0]))//如果是数字 进行转换 并压栈
{
temp = atoi(a[i].c_str());//进行数字转换 并压栈
st.push(temp);
}
else
{
if (a[i] == "find")
{
x = st.top(); st.pop();
n = st.top();st.pop();
stringstream sd;
sd << x;
string str = sd.str();
int k = s[n - 1].find(str);//改了 0
k = (k == string::npos ? s[n - 1].length() : k);
st.push(k);//执行find 的功能
}
else if (a[i] == "rfind")
{
int s2, n;
s2 = st.top();
st.pop();
n = st.top();
st.pop();
stringstream sd;
sd << s2;
string str = sd.str();
int k = s[n - 1].rfind(str);
k = (k == string::npos ? s[n - 1].length() : k);
st.push(k);//执行find 的功
}
else if (a[i] == "add")
{
string s2;
string c;
s1 = ss.top(); ss.pop();
s2= ss.top(); ss.pop();
if (isNum(s1) && isNum(s2))
{
int a = atoi(s1.c_str());
int b = atoi(s2.c_str());
char aa[100];
//10是十进制的意思
//openjudge上面,不能使用itoa和sprintf
// itoa(a+b, aa, 10);
// sprintf(aa, "%d", a+b);
strstream ss;
int sum = a + b;
ss << sum;
ss >> c;
}
else
c = s1 + s2;
ss.push(c);//执行find 的功
}
else if (a[i] == "copy")
{
string t;
int n,x, l;
n = st.top(); st.pop();
x = st.top(); st.pop();
l = st.top(); st.pop();
t = s[n - 1].substr(x, l);
ss.push(t);//执行find 的功
}
else if (a[i] == "reset")
{//将第n个字符串变为s
string s2 = ss.top(); ss.pop();
int n= st.top(); st.pop();
s[n - 1] = s2;
}
else if (a[i] == "insert")
{
s1 = ss.top(); ss.top();
int n, x;
n = st.top(); st.pop();
x= st.top(); st.pop();
s[n - 1].insert(x, s1);
}
else if (a[i] == "print")
{
int n = st.top(); st.pop();
cout << s[n - 1];
cout << endl;
}
else
{
ss.push(a[i]);
}
}
}
}
}
} while (b != "over");
return 0;
}