用c++写 线性表链式存储结构下基本操作的实现(初始化、建表、取值、查找、插入、删除、两个非递减有序链表的归并等
时间: 2024-10-11 11:02:42 浏览: 44
在C++中,线性表链式存储结构的基本操作通常涉及到`Node`类的设计,包含数据域和指向下一个节点的指针。以下是这些操作的简单实现:
```cpp
#include <iostream>
// 定义链表节点结构体
struct Node {
int data;
Node* next;
};
// 初始化一个空链表
Node* createList() {
return nullptr;
}
// 创建一个新的链表节点并插入元素
Node* insert(Node*& head, int value) {
if (head == nullptr) {
head = new Node{value, nullptr};
} else {
Node* newNode = new Node{value, head->next};
head->next = newNode;
}
return head;
}
// 取值操作(遍历)
int getValue(const Node* node) {
if (node != nullptr) {
return node->data;
} else {
std::cout << "链表为空" << std::endl;
return -1; // 返回默认值或抛出异常
}
}
// 查找特定值
Node* find(const Node* head, int value) {
Node* current = head;
while (current != nullptr) {
if (current->data == value) {
return current;
}
current = current->next;
}
return nullptr;
}
// 删除某个节点(这里仅考虑头节点)
void deleteNode(Node*& head, int value) {
if (head != nullptr && head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
}
}
}
// 归并两个非递减有序链表
Node* mergeSortedLists(Node* list1, Node* list2) {
if (list1 == nullptr) return list2;
if (list2 == nullptr) return list1;
if (list1->data <= list2->data) {
list1->next = mergeSortedLists(list1->next, list2);
return list1;
} else {
list2->next = mergeSortedLists(list1, list2->next);
return list2;
}
}
// 打印链表
void printList(const Node* node) {
while (node != nullptr) {
std::cout << node->data << " -> ";
node = node->next;
}
std::cout << "nullptr\n";
}
阅读全文