没有头结点的链表如何置空用c++代码举例
在没有头结点的链表中,可以通过将链表的第一个节点置为NULL来实现置空操作。以下是用C++代码举例:
#include <iostream>
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 置空链表
void clearList(ListNode*& head) {
ListNode* curr = head;
while (curr != NULL) {
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
head = NULL;
}
// 输出链表元素(用于验证)
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
std::cout << curr->val << " ";
curr = curr->next;
}
std::cout << std::endl;
}
int main() {
// 创建链表:1 -> 2 -> 3 -> 4
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
head->next = node2;
node2->next = node3;
node3->next = node4;
std::cout << "Before clear: ";
printList(head);
// 置空链表
clearList(head);
std::cout << "After clear: ";
printList(head); // 输出为空
return 0;
}
代码中,使用clearList函数来置空链表,通过循环遍历链表中的每一个节点,删除节点并释放内存,最后将头指针head置为NULL。printList函数用于验证链表是否已经置空。运行上述代码,输出结果如下:
Before clear: 1 2 3 4
After clear:
可以看到,链表成功被置空。
原文地址: https://www.cveoy.top/t/topic/i5ji 著作权归作者所有。请勿转载和采集!