第二章 链表part01
203.移除链表元素
Code :
/**标签:pre,ListNode,val,part01,next,链表,int,第二章 From: https://www.cnblogs.com/brinisky/p/17872029.html
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* p = head;
ListNode* pre;
ListNode* NewHead;
while(p != nullptr && p->val == val)
{
p = p->next;
}
NewHead = p;
pre = p;
while(p != nullptr)
{
//内循环
if(p->val == val)
{
pre->next = p->next;
}
else
{
pre = p;
}
p = p->next;
}
return NewHead;
}
};