#include<iostream>
#include<list>
using namespace std;
struct ListNode {
int val; // 节点上存储的元素
ListNode* next; // 指向下一个节点的指针
ListNode(int x) : val(x), next(NULL) {} // 节点的构造函数
};
// 根据数组创建链表函数
ListNode* Arr2Chain(int a[], int num)
{
// head point
ListNode* head = NULL; // newand malloc 两种方式申请内存
//tail point
ListNode* tail = NULL;
ListNode* add = NULL;
for (int i = 0; i < num; ++i)
{
ListNode* add = new ListNode(a[i]);
// TreeNode *add= (TreeNode*)malloc(sizeof(TreeNode));
// headd->val =a[i];
// headd->next =NULL;
if (tail != NULL)
{
tail->next = add;
tail = add;
}
else
{
head = tail = add;
}
}
return head;
}
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) // 链表移除函数
{
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点,并将其值初始化为0
dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
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;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
int main() {
int a[] = { 0,1,2,3,4,5,6,7,8,9,2,3,2 };
int num = sizeof(a) / sizeof(a[0]);
ListNode* head = Arr2Chain(a, num);
Solution s;
ListNode* m_head = s.removeElements(head, 2);
while (m_head != NULL)
{
cout << m_head->val << " ";
m_head = m_head->next;
}
return 0;
}
标签:head,ListNode,cur,int,next,链表,移除,NULL
From: https://www.cnblogs.com/dh2021/p/16829690.html