203. 移除链表元素
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
/**
* 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* dummy = new ListNode();
dummy->next = head;
ListNode* cur = dummy;
while(cur->next != nullptr){
//每次判断cur的下一个
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}else{
cur = cur->next;
}
}
head = dummy->next;
delete dummy;
return head;
}
};