C++ 单链表操作:查询、插入、删除
C++ 单链表操作:查询、插入、删除
本示例使用 C++ 代码实现单链表数据结构,并提供查询、插入、删除等操作的函数。代码包含详细注释,并提供示例演示如何使用这些函数。
#include <iostream>
// 单链表节点结构
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 查询链表中是否存在某个值
bool search(ListNode* head, int target) {
ListNode* curr = head;
while (curr != nullptr) {
if (curr->val == target) {
return true;
}
curr = curr->next;
}
return false;
}
// 在链表的指定位置插入一个节点
void insert(ListNode*& head, int position, int value) {
if (position < 0) {
std::cout << 'Invalid position!' << std::endl;
return;
}
ListNode* newNode = new ListNode(value);
if (position == 0) {
newNode->next = head;
head = newNode;
} else {
ListNode* curr = head;
int count = 0;
while (curr != nullptr && count < position - 1) {
curr = curr->next;
count++;
}
if (curr == nullptr) {
std::cout << 'Invalid position!' << std::endl;
return;
}
newNode->next = curr->next;
curr->next = newNode;
}
}
// 删除链表中指定位置的节点
void remove(ListNode*& head, int position) {
if (head == nullptr) {
std::cout << 'List is empty!' << std::endl;
return;
}
if (position == 0) {
ListNode* temp = head;
head = head->next;
delete temp;
} else {
ListNode* curr = head;
int count = 0;
while (curr->next != nullptr && count < position - 1) {
curr = curr->next;
count++;
}
if (curr->next == nullptr) {
std::cout << 'Invalid position!' << std::endl;
return;
}
ListNode* temp = curr->next;
curr->next = curr->next->next;
delete temp;
}
}
// 打印链表
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != nullptr) {
std::cout << curr->val << ' ';
curr = curr->next;
}
std::cout << std::endl;
}
int main() {
ListNode* head = nullptr;
insert(head, 0, 1);
insert(head, 1, 2);
insert(head, 2, 3);
printList(head); // 输出: 1 2 3
std::cout << 'Search 2: ' << (search(head, 2) ? 'Found' : 'Not Found') << std::endl; // 输出: Found
std::cout << 'Search 4: ' << (search(head, 4) ? 'Found' : 'Not Found') << std::endl; // 输出: Not Found
remove(head, 1);
printList(head); // 输出: 1 3
return 0;
}
以上代码实现了一个简单的单链表数据结构,并提供了查询、插入、删除等操作的函数。在main函数中,我们创建了一个链表并进行了一些操作,包括插入节点、查询是否存在某个值、删除节点等。最后,打印链表的内容以验证操作的正确性。
原文地址: http://www.cveoy.top/t/topic/pb1l 著作权归作者所有。请勿转载和采集!