#include <iostream>
#include <vector>
class ListNode {
public:
int val;
ListNode *next;
//构造函数,采用列表形式赋值
ListNode(int x) : val(x), next(NULL) {}
//创建测试用例的构造函数,将vector类型传入listNode
ListNode(std::vector<int> arr) {
if (arr.empty() ) {
std::cout << "error" << std::endl;
}
this->val = arr[0];
ListNode* cur = this;
for (int i = 1; i < arr.size(); i++) {
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);//创建虚拟头结点
dummyHead->next = head;
ListNode* pri = dummyHead;
while (pri->next != nullptr) {
if (pri->next->val == val) {
ListNode* toRemove = pri->next;
pri->next = pri->next->next;
}
else
pri = pri->next;//注意,仅在不删除节点时执行该语句,否则会错过下一个节点
}
return dummyHead->next;
}
};
int main()
{
std::vector<int> arr = { 1,1,1,1,1,1 };
ListNode* head = new ListNode(arr);
//循环输出ListNode,注意判断条件 prev != NULL
for(ListNode* prev=head;prev != NULL;prev = prev->next)
std::cout << prev->val ;
std::cout << std::endl;
ListNode* res = (new Solution())->removeElements(head, 1);
for (ListNode* prev = res; prev != NULL; prev = prev->next)
std::cout << prev->val;
std::cout << std::endl;
}