#include <iostream>
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 插入节点到链表尾部
void insertNode(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
if (head == nullptr) {
head = newNode;
} else {
ListNode* curr = head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 打印链表
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != nullptr) {
std::cout << curr->val << " ";
curr = curr->next;
}
std::cout << std::endl;
}
// 删除链表中的指定值节点
void deleteNode(ListNode*& head, int val) {
// 创建一个虚拟节点作为头节点
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* prev = dummy;
ListNode* curr = head;
while (curr != nullptr) {
if (curr->val == val) {
// 删除当前节点
prev->next = curr->next;
delete curr;
// 如果只想删除一个特定值的节点,可以在这里添加 break 语句
}
prev = curr;
curr = curr->next;
}
// 更新链表头节点
head = dummy->next;
delete dummy;
}
int main() {
ListNode* head = nullptr;
// 插入节点
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
insertNode(head, 4);
insertNode(head, 5);
// 打印链表
std::cout << "Original linked list: ";
printList(head);
// 删除节点值为3的节点
deleteNode(head, 3);
// 打印删除后的链表
std::cout << "Linked list after deleting node with value 3: ";
printList(head);
return 0;
}
c++ 链表操作
最新推荐文章于 2024-11-05 17:16:24 发布