今天完成了C语言作业,学习了有关链表的知识;其中部分代码如下:
include
include
using namespace std;
// 定义链表节点
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
// 定义链表
class LinkedList {
public:
Node* head = nullptr;
// 插入节点
void insert(int k, int d) {
Node* newNode = new Node(d);
if (k == 0) {
newNode->next = head;
head = newNode;
} else {
Node* current = head;
for (int i = 1; current != nullptr && i < k; i++) {
current = current->next;
}
if (current != nullptr) {
newNode->next = current->next;
current->next = newNode;
}
}
}
// 删除节点
void remove(int k) {
if (k == 1 && head) {
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* current = head;
for (int i = 1; current != nullptr && i < k - 1; i++)
current = current->next;
if (current && current->next) {
Node* temp = current->next;
current->next = temp->next;
delete temp;
}
}
}
// 打印链表
void print() {
Node* current = head;
while (current) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
int n, m, k, d, op;
cin >> n;
LinkedList list;
for (int i = 0; i < n; i++) {
cin >> d;
list.insert(i, d);
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> op;
if (op == 0) {
cin >> k >> d;
list.insert(k, d);
} else if (op == 1) {
cin >> k;
list.remove(k);
}
}
list.print();
return 0;
}