题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include <iostream>
using namespace std;
struct list {
int data;
list* next;
};
void insert(list* p, int x, int y) {
list* q = p;
p = p->next;
while (p != NULL) {
//插入操作放于循坏外,能够在x值不存在情况下把节点插入最后
if (p->data == x)
break;
q = p;
p = p->next;
}
list* t = new list();
t->data = y;
q->next = t;
t->next = p;
}
void del(list* p, int x) {
list* q = p;
p = p->next;
while (p != NULL) {
//如果将删除操作放在循环外,可能删除空列表,因而确定有x再执行删除操作
if (p->data == x)
{
q->next = p->next;
p->next = NULL;
delete p;
break;
}
q = p;
p = p->next;
}
}
int main() {
int n;
cin >> n;
list* head = new list();
head->next = NULL;
while (n--) { // 注意 while 处理多个 case
string s;
int x, y;
cin >> s;
if (s == "insert") {
cin >> x >> y;
insert(head, x, y);
}
if (s == "delete") {
cin >> x;
del(head, x);
}
}
list* t = head->next;
if (t == NULL)
cout << "NULL";
else while (t != NULL) {
cout << t->data << " ";
t = t->next;
}
}
// 64 位输出请用 printf("%lld")
阿里云成长空间 695人发布
