ZBLOG

// 销毁链表(释放内存) void destroyList(Node** pHead) { clearList(pHead); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]);请将以上c语言代码用c++语言来实现

以下是使用C++语言来实现的代码:

#include <iostream>

struct Node {
    int data;
    Node* next;
};

void clearList(Node** pHead) {
    while (*pHead != nullptr) {
        Node* temp = *pHead;
        *pHead = (*pHead)->next;
        delete temp;
    }
}

void destroyList(Node** pHead) {
    clearList(pHead);
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    // 创建链表
    Node* head = nullptr;
    Node* current = nullptr;

    for (int i = 0; i < n; ++i) {
        Node* newNode = new Node();
        newNode->data = arr[i];
        newNode->next = nullptr;

        if (head == nullptr) {
            head = newNode;
            current = newNode;
        } else {
            current->next = newNode;
            current = newNode;
        }
    }

    // 销毁链表
    destroyList(&head);

    return 0;
}

这段代码将数组 {1, 2, 3, 4, 5} 转换为一个链表,并通过 destroyList 函数销毁了该链表。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8850

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?