C++线性表链式存储结构下基本操作的实现(初始化、建表、取值、查找、插入、删除、两个非递减有序链表的归并等)。
时间: 2024-10-10 21:15:26 浏览: 48
解析C++的线性表链式存储设计与相关的API实现
在C++中,线性表的链式存储结构通常用于实现动态数据结构,因为它允许元素的动态添加和删除。以下是基本操作的一些实现:
1. **初始化**:
创建一个链表头节点(通常是空指针),`struct Node* head = nullptr;`
2. **建表(插入首元素)**:
```cpp
void createList(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head = newNode;
}
```
3. **取值(访问元素)**:
```cpp
int getValue(Node* node) {
if (node != nullptr) {
return node->data;
} else {
throw std::runtime_error("Element not found");
}
}
```
4. **查找(遍历查找特定值)**:
```cpp
Node* findValue(int value, Node* head) {
while (head != nullptr && head->data != value) {
head = head->next;
}
return head;
}
```
5. **插入**:
```cpp
void insert(int value, Node*& head) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head = newNode;
}
```
6. **删除**:
```cpp
void deleteNode(Node*& head, int value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* temp = current->next;
current->next = temp->next;
delete temp;
}
}
```
7. **两个非递减有序链表的归并**:
```cpp
void mergeSortedLists(Node*& list1, Node*& list2, Node*& result) {
Node* temp1 = list1, *temp2 = list2, *resultHead = nullptr;
while (temp1 != nullptr && temp2 != nullptr) {
if (temp1->data <= temp2->data) {
resultHead = temp1;
temp1 = temp1->next;
} else {
resultHead = temp2;
temp2 = temp2->next;
}
}
if (temp1 != nullptr) {
resultHead->next = temp1;
} else {
resultHead->next = temp2;
}
list1 = resultHead;
}
```
阅读全文