单向链表操作
时间限制:1 s内存限制:128 MB
模拟单向链表,刚开始链表中只有1个数据为0。有n个操作属于下列两个之一:
1 x y:表示找到链表中x的位置,并在之后插入y,如果x不存在或者y已经存在,输出“error”,否则输出"ok"
2 x: 删除链表中的数x(x≠0),把它删除,如果x不存在,输出"error",否则输出"ok"
n次操作结束之后,从左到右输出链表中的每个数。
输入
第一行一个整数n,表示操作次数。
接下来n行,每行格式如上操作中之一。
输出
对于每个操作,输出相应的结果。
最后输出链表中的每个数。
我要用list<int>做,但是插入和删除有点问题
然后就不知道了,我的code:
#include<bits/stdc++.h>
using namespace std;
int main() {
list<int>s;
int t;
cin >> t;
while (t--) {
int op;
cin >> op;
if (op == 1) {
int x, y;
cin >> x >> y;
list<int>::iterator it = s.begin();
for (int i = 1; i < x-1; i++) {
it++;
}
s.insert(it, y);
cout << "ok" << endl;
} else {
int x;
cin >> x;
int flag = 0;
for (auto a = s.begin(); a != s.end(); a++) {
if (*a == x) {
flag = 1;
cout << "ok" << endl;
s.erase(a);
break;
}
}
if (flag == 0) {
cout << "error" << endl;
}
}
}
cout<<0<<" ";
for(auto a=s.begin();a!=s.end();a++){
cout<<*a<<" ";
}
return 0;
}