天天看点

【C++项目实战】链表创建和内存释放

代码

#include<iostream>
using namespace std;
struct Node{
    int val;
    Node *next, *random;
    Node(int x): val(x), next(nullptr), random(nullptr){};
    void DeleteList(){
        Node*p=this;
        Node*head;
        if(p){
            int val = p->val;
            head=p->next;
            delete p;
            cout<<"delete the link of " << val <<  endl;
            if(head)
            	head->DeleteList(); // 递归释放内存
        }
    }
};
int main(){
    Node *head = new Node(0);
    Node *p1 = head; 
    for (int i=1; i<5; ++i){
        p1->next = new Node(i);    
        p1 = p1->next;  
    }
    head->DeleteList();
}
           

输出内容

delete the link of 0
delete the link of 1
delete the link of 2
delete the link of 3
delete the link of 4