AcWing 826. 单链表
原题链接
简单
作者:
不知道取啥名_1
,
2024-11-06 18:18:40
,
所有人可见
,
阅读 2
算法1 动态链表
C++ 代码
#include<iostream>
#include<vector>
using namespace std;
struct Node
{
int val;
Node* next;
Node(int x) : val(x), next(nullptr) {}
};
class Mylist {
public:
Mylist() : head(nullptr), v() {}
public:
void addhead(int x) {
Node* u = new Node(x);
u->next = head;
head = u;
v.push_back(u);
}
void deleteh(int k) {
if (k == 0) head = head->next;
else {
Node* r = v[k - 1];
Node* pre = v[k - 1]->next;
if (pre->next && pre) r->next = pre->next;
else r->next = nullptr;
}
}
void assertafter(int k, int j) {
Node* newnode = new Node(j);
v.push_back(newnode);
newnode->next = v[k-1]->next;
v[k-1]->next = newnode;
}
void printList() {
Node* current = head;
while (current) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
}
private:
Node* head;
vector <Node*> v;
};
int main() {
int num, a, b;
char c;
cin >> num;
Mylist mylist;
for (int i = 0; i < num; i++) {
cin >> c;
if (c == 'H') {
cin >> a;
mylist.addhead(a);
}
if (c == 'D') {
cin >> a;
mylist.deleteh(a);
}
if (c == 'I') {
cin >> a >> b;
mylist.assertafter(a, b);
}
}
mylist.printList();
return 0;
}