题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f?tpId=308&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308
#include <iostream>
using namespace std;
#include<algorithm>
#include <string>
class stack {
private:
int s[10000];
int top = -1;
public:
void insert(int x, int y)
{
if(top>=0) //非空
{
for(int i=0;i<=top;i++) //遍历
{
if(s[i]==x)//存在x
{
top++;
for(int j=top;j>i;j--)
{
s[j]=s[j-1]; //x后的数组后移一位
}
s[i]=y;
break; //一定要结束循环,不然top会不断增加
}
else if ((s[i]!=x) && (i==top)) //遍历到最后一个数还不是x
{
top++;
s[top]=y; //加到尾部
break; //一定要结束循环,不然top会不断增加
}
}
}
else //空
{
top++;
s[top]=y; //加尾部
}
}
void delete1(int x)
{
if(top>=0) //非空,空的话不理它
{
for(int i=0;i<=top;i++) //遍历
{
if(s[i]==x) //存在x,不存在x的就不理它
{
top--;
for(int j=i;j<=top;j++)
{
s[j]=s[j+1]; //x后的数组前移一位
}
break; //一定要加结束
}
}
}
}
void out()
{
if(top>=0) //非空
{
for(int i=0;i<=top;i++)
{
cout<<s[i]<<" "; //遍历输出,不然会换行输出
}
cout<<endl;
}
else //空
{
cout<<"NULL"<<endl;
}
}
};
int main() {
// int a, b;
// while (cin >> a >> b) { // 注意 while 处理多个 case
// cout << a + b << endl;
// }
stack s;
int n = 0;
cin >> n;
for (int i = 0; i < n; i++) {
string op;
cin >> op;
if (op == "insert") {
int x = 0;
cin >> x;
int y = 0;
cin >> y;
s.insert(x, y);
}
if (op == "delete") {
int x = 0;
cin >> x;
s.delete1(x);
}
}
s.out();
return 0;
}
// 64 位输出请用 printf("%lld")
查看9道真题和解析