题解 | #【模板】链表#

【模板】链表

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")

全部评论

相关推荐

10-29 22:30
吉林大学 Java
同专业学长学姐,去互联网大厂的起薪&nbsp;15k+,去国企&nbsp;IT&nbsp;岗的也有&nbsp;12k+,就连去中小厂的都基本&nbsp;13k&nbsp;起步😤&nbsp;我投的传统行业技术岗,拼死拼活拿到&nbsp;1Woffer,本来还挺开心,结果逛了圈牛客直接破防,同是校招生,行业差距怎么就这么大啊!
喵喵喵6_6:应该哪里不对吧,大厂都是20k以上的,10k那种对于985本的学生基本就是点击一下过了笔试就送的,我前两天刚拿了一个11k,笔试完第2天就打电话了,非科班。坏消息是c++岗开这么低真是刷新认知了
校招生月薪1W算什么水平
点赞 评论 收藏
分享
想玩飞盘的菠萝蜜在春...:上交✌🏻也拒?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务