第一步:如果链表为空,直接返回空指针
第二步:把head移到head.val不等于val的地方
第三步:从当前head开始,判断它的 是不是等于val,如果等于val,那么
,否则直接推进
,直到head为空或者
/*
* @lc app=leetcode.cn id=203 lang=cpp
*
* [203] 移除链表元素
*/
// @lc code=start
// 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 head;
}
// ListNode* ans = new ListNode(-1); // 新建一个ListNode
while (head != nullptr) {
if (head->val == val) {
head = head->next; // 保证head.val不为val
}
else {
break;
}
}
ListNode* tmp = head; // head变换不影响tmp的值
// ans->next = tmp; // 指向head初始值
while (head != nullptr)
{
ListNode* now = head->next;
if (now == nullptr) break;
if (now->val == val) {
head->next = now->next;
}
else{
head = head->next;
}
}
return tmp;
}
};
// @lc code=end