实现线性表的链式存储定义,完成单链表的创建(头插法、尾插法)、插入、删除、查找等常用操作,将线性链表逆置,即最后一个结点变成第一个结点
时间: 2024-12-12 21:21:40 浏览: 7
线性链表是一种数据结构,其中元素通过链接的方式组织在一起,每个节点包含两个部分:数据域和指针域。在链式存储中,每个节点通常有一个指向下一个节点的引用,形成一个链式结构。
### 定义:
```cpp
// 节点定义
struct ListNode {
int val; // 数据域
ListNode* next; // 指针域,指向下一个节点
ListNode(int x) : val(x), next(nullptr) {} // 构造函数
};
// 链表定义
class LinkedList {
private:
ListNode* head; // 头节点指针
public:
LinkedList() : head(nullptr) {} // 构造函数,初始化为空链表
};
```
### 单链表的操作:
#### 1. 头插法创建链表
```cpp
void insertAtHead(int value) {
ListNode* newNode = new ListNode(value);
newNode->next = head;
head = newNode;
}
```
#### 2. 尾插法(也称尾部添加)
```cpp
void insertAtTail(int value) {
if (head == nullptr) {
head = new ListNode(value);
return;
}
ListNode* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = new ListNode(value);
}
```
#### 3. 插入节点
```cpp
void insertAfterNode(int value, int targetValue) {
ListNode* newNode = new ListNode(value);
ListNode* current = head;
while (current != nullptr && current->val != targetValue) {
current = current->next;
}
if (current != nullptr) {
newNode->next = current->next;
current->next = newNode;
} else {
std::cout << "Target node not found." << std::endl;
}
}
```
#### 4. 删除节点
```cpp
void deleteNode(int value) {
if (head == nullptr || head->val == value) {
ListNode* temp = head;
head = head->next;
delete temp;
return;
}
ListNode* current = head;
while (current->next != nullptr && current->next->val != value) {
current = current->next;
}
if (current->next != nullptr) {
ListNode* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
} else {
std::cout << "Node not found." << std::endl;
}
}
```
#### 5. 查找节点
```cpp
ListNode* searchNode(int value) {
ListNode* current = head;
while (current != nullptr) {
if (current->val == value) {
return current;
}
current = current->next;
}
return nullptr; // 如果未找到,返回nullptr
}
```
#### 6. 线性链表逆置
```cpp
void reverseList() {
ListNode* prev = nullptr;
ListNode* current = head;
ListNode* nextTemp = nullptr;
while (current != nullptr) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
head = prev; // 更新头节点
}
```
阅读全文