2010年北理复试上机题
1、输入一串整数,输入指令。
要求:(1)输入a t,在这串整数后添加整数t。(2)输入c\m\n,用n替换m。(3)输入d t,删除t。(4)输入s排序。
为什么使用cin.clear(),因为之前输入Crtl+Z将cin.fail()置1,cin无法正常读取,所以要使其回归正常状态。
#include<iostream> #include<vector> #include<algorithm> using namespace std; vector<int> v; vector<int>::iterator i; void show() { cout << "目前的这串整数为:"; for (i = v.begin(); i != v.end(); i++)cout << *i << " "; cout << endl; } void replace(int m,int n) { for (i = v.begin(); i != v.end(); i++) { if (*i == m)*i = n; } } void del(int t) { for (i = v.begin(); i != v.end(); i++) { if (*i == t)v.erase(i); } } int main() { cout << "请输入一串整数,Ctrl+Z结束" << endl; int a; while (cin >> a)v.push_back(a); cout << "输入指令:1.a t(在整数串后面添加t) 2.c\\m\\n(用n替换m) 3.d t(删除t) 4.s(排序) 5.Ctrl+Z(结束)" << endl; cin.clear();//清空之前的cin状态标识符 char c; while (cin >> c) { if (c == 'a') { int t; cin >> t; v.push_back(t); show(); } if (c == 'c') { int m, n; getchar(); cin >> m; getchar(); cin >> n; replace(m, n); show(); } if (c == 'd') { int t; cin >> t; del(t); show(); } if (c == 's') { sort(v.begin(), v.end()); show(); } } return 0; }
2、输入表达式,输出值。中缀表达式求值:先将中缀表达式建立二叉树转后缀表达式,然后再求值。
#include<cstdio> #include<cstring> #include<iostream> #include<stack> using namespace std; int priority(char c) { if (c == '+' || c == '-')return 0; else if (c == '*' || c == '/')return 1; } int main() { char in[205]; char post[205] = { 0 }; stack<char> s; scanf("%s", in); int l = strlen(in); int size = 0; for (int i = 0; i < l; i++) { if (in[i] >= '0'&&in[i] <= '9')post[size++] = in[i]; else if (in[i] == '(')s.push(in[i]); else if (in[i] == ')') { if (s.empty()) { printf("Wrong!\n"); return 0; } while (s.top() != '(') { post[size++] = s.top(); s.pop(); } if (s.top() != '(')printf("Wrong!/n"); else s.pop();//弹出开括号 } else if (in[i] == '*' || in[i] == '/' || in[i] == '+' || in[i] == '-') { while (!s.empty() && priority(s.top()) >= priority(in[i]) && s.top() != '(') { post[size++] = s.top(); s.pop(); } s.push(in[i]); } } while (!s.empty()) { post[size++] = s.top(); s.pop(); } cout<<post<<endl; stack<int> ans; int len = strlen(post); for (int i = 0; i < len; i++) { if (post[i] >= '0'&&post[i] <= '9')ans.push(post[i] - '0'); else { int b = ans.top(); ans.pop(); int a = ans.top(); ans.pop(); int c; if (post[i] == '+')c = a + b; else if (post[i] == '-')c = a - b; else if (post[i] == '*')c = a * b; else if (post[i] == '/')c = a / b; ans.push(c); } } printf("%d\n", ans.top()); system("pause"); return 0; }

浙公网安备 33010602011771号