题解 | #【模板】链表#

【模板】链表

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

#include <bits/stdc++.h>
using namespace std;
struct Node
{
    int v;
    Node *next;
    Node(int x): v(x), next(NULL) {}
};
int main()
{
    int n, a, b;
    string s;
    cin>>n;
    Node *dummy = new Node(-1);
    while (n--) {
        cin>>s>>a;
        if (s == "delete") {
            Node *q = dummy->next;
            if (!q) continue;
            Node *pre = dummy;
            while (q) {
                if (q->v == a) {
                    pre->next = q->next;
                    break;
                }
                q = q->next;
                pre = pre->next;
            }
        } else if (s == "insert") {
            cin>>b;
            Node *q = dummy->next;
            bool flag = true;
            if (!q) {
                dummy->next = new Node(b);
                continue;
            }
            while (q) {
                if (q->v == a) {
                    Node *tmp = new Node(a);
                    tmp->next = q->next;
                    q->next = tmp;
                    q->v = b;
                    flag = false;
                    break;
                }
                if (!q->next && flag) {
                    q->next = new Node(b);
                    break;
                }
                q = q->next;
            }
        }
        
    }
    Node *q = dummy->next;
    if (!q) cout<<"NULL"<<endl;
    else {
        while (q) {
            cout<<q->v<<" ";
            q = q->next;
        }
    }
    
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
10-29 15:38
门头沟学院 Java
榕城小榕树:难道你简历里写了配送路径优化算法?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务