题解 | #【模板】链表#

【模板】链表

https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f

#include <cstddef>
#include <iostream>
#include <list>
using namespace std;

struct mylist
{
    int data;
    mylist* next;
};

void insert(mylist* p,int x,int y)
{
   mylist* q =p;
   p = p->next;
   while(p!=NULL)
   {
        if(p->data == x)
        {
            break;
        }
        q = p;
        p = p->next;
   } 
   mylist* t = new mylist;

    t->data = y;
    t->next = p;
    q->next = t;
}

void del(mylist* p,int x)
{
    mylist*q = p;
    p = p->next;
    while(p!=NULL)
    {
        if(p->data == x)
        {
            q->next = p->next;
            p->next = NULL;
            delete p;
            return;
        }
        q=p;
        p=p->next;
    }
}

int main() 
{
    int n = 0;
    cin>>n;
    
    mylist* head = new mylist;
    head->next = NULL;
    for(int i =0;i<n;i++)
    {
        string res;
        cin>>res;
        if(res == "insert")
        {
            int x,y;
            cin>>x>>y;
            insert(head,x,y);
        }
        else if(res == "delete")
        {
            int x;
            cin>>x;
            del(head, x);
        }
    }
    if(head->next == NULL)
    cout<<"NULL"<<endl;
    while(head->next!=NULL)
    {
        cout<<head->next->data<<" ";
        head->next =head->next->next;
    }
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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