题解 | 【模板】链表
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include <iostream>
using namespace std;
class LinkNode {
public:
int val;
LinkNode* next;
LinkNode(int x): val(x), next(nullptr) {}
};
class LinkList {
public:
LinkNode* head;
LinkList() {
head = nullptr;
}
void insert(int x, int y) {
LinkNode* tem = new LinkNode(y);
if (head == nullptr) {
head = tem;
return;
}
LinkNode* pre = new LinkNode(0);
pre->next = head;
LinkNode* h = head;
head = pre;
while (h != nullptr) {
if (h->val == x) {
tem->next = h;
pre->next = tem;
head = head->next;
return ;
} else {
pre = pre->next;
h = h->next;
}
}
pre->next=tem;
head=head->next;
}
void Delete(int x) {
LinkNode* pre = new LinkNode(0);
pre->next = head;
LinkNode* h = head;
head = pre;
while (h != nullptr) {
if (h->val == x) {
pre->next = h->next;
head = head->next;
return ;
} else {
h = h->next;
pre = pre->next;
}
}
head = head->next;
}
};
int strToInt(string s) {
int count = 0;
int n = s.size();
for (int i = 0; i < n; i++) {
count = count * 10 + (s[i] - '0');
}
return count;
}
int main() {
int n;
cin >> n;
getchar();
LinkList l;
for (int i = 0; i < n; i++) {
string str;
getline(cin, str);
string s = str.substr(0, 7);
if (s == "insert ") {
string s1 = str.substr(7);
int a = s1.find(' ');
int x = strToInt(s1.substr(0, a));
int y = strToInt(s1.substr(a + 1));
l.insert(x, y);
} else {
string s1 = str.substr(7);
int x = strToInt(s1);
l.Delete(x);
}
}
if(l.head==nullptr)
{
cout<<"NULL"<<endl;
}
while(l.head!=nullptr)
{
cout<<l.head->val<<" ";
l.head=l.head->next;
}
return 0;
}
// 64 位输出请用 printf("%lld")
