【刷题-LeetCode】203. Remove Linked List Elements
- Remove Linked List Elements
Remove all elements from a linked list of integers that have value *val*.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
解
/**
* 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(0, head);
ListNode *pre = dummy, *cur = head;
while(cur){
if(cur->val == val){
pre->next = cur->next;
cur = cur->next;
}else{
pre = cur;
cur = cur->next;
}
}
return dummy->next;
}
};
作者:Vinson
-------------------------------------------
个性签名:只要想起一生中后悔的事,梅花便落满了南山
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!