# 定义链表结构体

``````struct ListNode
{
int val;
ListNode *next;
ListNode(int val1, ListNode *next1 = nullptr)
{
val = val1;
next = next1;
}
};
``````

# 定义创建链表类

``````class List
{
public:
ListNode *numberList;
List()
{
numberList = nullptr;
}
~List()
{
ListNode *n;
while (numberList != nullptr)
{
n = numberList;
numberList = numberList->next;
delete n;
}
cout << "congradgulations!" << endl;
}

ListNode *creat(int array[], int len)
{

for (int i = 0;i < len;i++)
{
numberList = new ListNode(array[i], numberList);
}
return numberList;
}
void print()
{
ListNode *nm = numberList;
while (nm != nullptr)
{
cout << nm->val << endl;
nm = nm->next;
}
cout << "hello" << endl;
}
};
``````

# 书写头文件

#define LISTNODE_H

#endif

``````#pragma once
#ifndef LISTNODE_H
#define LISTNODE_H
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int val1, ListNode *next1 = nullptr)
{
val = val1;
next = next1;
}
};
class List
{
public:
ListNode *numberList;
List()//构造函数
{
numberList = nullptr;
}
~List()//析构函数
{
ListNode *n;
while (numberList != nullptr)
{
n = numberList;
numberList = numberList->next;
delete n;
}
cout << "congradgulations!" << endl;
}

ListNode *creat(int array[], int len)
{

for (int i = 0;i < len;i++)
{
numberList = new ListNode(array[i], numberList);//链表节点的地址和数组中的地址有关系吗
}
return numberList;
}
void print()
{
ListNode *nm = numberList;
while (nm != nullptr)
{
cout << nm->val << endl;
nm = nm->next;
}
cout << "hello" << endl;
}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode* dummyHead = new ListNode(0);
ListNode* cur = dummyHead;
while (cur->next != NULL) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else {
cur = cur->next;
}
}
}
};
void creat(int array[], int len);
void print();
struct ListNode;
class List;
ListNode* removeElements(ListNode* head, int val);

#endif

``````

# 源文件与main函数

``````#include<iostream>
#include"ListNode.h"
using namespace std;
//ListNode* removeElements(ListNode* head, int val);

int main()
{
List *l=new List();
Solution s;
int a[] = {  1,2,3,4,5,6 };
int len = sizeof(a) / sizeof(int);
ListNode *number = l->creat(a, len);
s.removeElements(number, 3);
l->print();
delete l;
system("pause");
return 0;
}
``````

# new与delete

*creat()函数中使用了new命令在堆区创建了空间，由于堆区的空间需要手动创建和手动释放，因此我们需要使用delete来调用析构函数，否则会造成内存泄漏错误。

# 初学C++的感想

原文作者：wolf-tl
原文地址: https://blog.csdn.net/weixin_43716907/article/details/121180549
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。