单链表节点的删除:本题要求实现两个函数,分别将读取的数据储存为单链表、将链表中所有储存了某给定值的节点删除。链表节点定义如下: struct ListNode{ int data; ListNode *next; };
时间: 2024-11-05 22:28:03 浏览: 42
单链表是一种线性的数据结构,每个节点包含数据元素和指向下一个节点的指针。对于节点的删除操作,主要有两种情况:
1. 删除特定数据值的节点:
- 首先,需要遍历链表,找到第一个存储目标数据值的节点(如果存在的话)。这通常通过一个`while`循环实现,同时维护两个指针:当前节点(current)和前一个节点(previous),当遇到目标值时,记录当前节点,然后更新前一个节点的`next`指针为当前节点的`next`,跳过当前节点。
```cpp
ListNode* deleteNodes(ListNode* head, int target) {
if (!head || !head->next) return nullptr; // 如果链表为空或只有一个节点,直接返回
ListNode* current = head;
while (current && current->data != target) {
previous = current;
current = current->next;
}
if (!current) return head; // 没有找到目标节点,返回原链表
if (previous == nullptr) head = current->next; // 目标是头节点,更新头指针
else previous->next = current->next; // 删除当前节点
delete current; // 释放内存
return head;
}
```
2. 删除整个链表(即仅保留非目标值节点):
- 这种情况下,需要创建一个新的链表头,并在遍历过程中替换旧链表的头指针。
```cpp
ListNode* deleteAllNodes(ListNode* head, int target) {
if (!head) return nullptr;
ListNode* newHead = nullptr, *current = head;
while (current) {
if (current->data != target) {
if (!newHead) newHead = current;
else newHead->next = current;
}
current = current->next;
}
head = newHead;
return head;
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)