题解 | #【模板】链表#
【模板】链表
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;
}