一、题目
二、思路
基础题,从头到尾遍历链表节点元素,遇到目标节点就删除。
一开始没用哨兵节点,处理第一个元素是目标结点,和处理第一个和第二个元素为目标结点,这两种情况处理起来有点冗余,,只过了44个测试用例:
/** * 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* slow = head; ListNode* fast = head; if(fast == NULL){ return head; } fast = fast->next; if(fast == NULL && slow->val == val){ return NULL; }else if(fast != NULL && slow->val == val){ slow = slow ->next; fast = fast->next; head = slow->next; } while(fast != NULL){ if(fast->val == val){ slow->next = fast->next; fast = fast->next; continue; } fast = fast->next; slow = slow->next; } return head; } };