以下是一个 C++ 代码的例子,将链表的头指针指向 null:

#include <iostream>

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

void deleteLinkedList(ListNode* &head) {
    ListNode* curr = head;
    while (curr != NULL) {
        ListNode* temp = curr;
        curr = curr->next;
        delete temp;
    }    
    head = NULL; // 将头指针指向 null
}

int main() {
    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    
    deleteLinkedList(head);
    
    if (head == NULL) {
        std::cout << '链表已删除' << std::endl;
    }
    
    return 0;
}

在上面的例子中,我们首先创建一个简单的链表,然后调用deleteLinkedList函数来删除链表。该函数使用一个循环来遍历链表,删除每个节点,并将头指针指向 null。在最后的检查中,我们可以看到头指针已经指向 null,表明链表已经被成功删除。

C++ 链表删除:将头指针指向 null 的代码示例

原文地址: https://www.cveoy.top/t/topic/mPaI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录