删除当前指针所指链表后面的所有链表的代码
时间: 2023-07-23 18:57:29 浏览: 51
以下是一个示例代码,用于删除当前指针所指链表后面的所有链表:
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
// 删除链表的所有节点
void deleteLinkedList(Node* head) {
Node* current = head;
Node* nextNode;
while (current != nullptr) {
nextNode = current->next;
delete current;
current = nextNode;
}
}
// 删除当前指针所指链表后面的所有链表
void deleteRemainingLinkedList(Node* current) {
if (current == nullptr || current->next == nullptr) {
return;
}
// 遍历到链表末尾
while (current->next != nullptr) {
current = current->next;
}
// 删除链表的所有节点
deleteLinkedList(current->next);
// 将当前指针的next设为nullptr,表示删除后面的链表
current->next = nullptr;
}
int main() {
// 创建链表
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
head->next->next->next = new Node{4, nullptr};
head->next->next->next->next = new Node{5, nullptr};
// 当前指针指向第二个节点
Node* current = head->next;
// 删除当前指针所指链表后面的所有链表
deleteRemainingLinkedList(current);
// 打印剩余链表
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
// 释放内存
deleteLinkedList(head);
return 0;
}
```
请注意,这只是一个示例代码,根据实际情况可能需要进行适当的调整。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)