- Remove Linked List Elements
Delete all nodes in the linked list that are equal to the given value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5 Create a pseudo-head by
linking the original question
Node:
/**
* 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) {
if (head == nullptr)
return nullptr;
ListNode* sentr = new ListNode();//申请一个伪头结点
sentr->next = head;
ListNode* prear = sentr;
ListNode* pfro = head;
while (pfro) {
if (pfro->val == val) {
prear->next = pfro->next;
pfro=pfro->next;
}
else{
prear = prear->next;
pfro = pfro->next;
}
}
return sentr->next;
}
};