题目链接:https://leetcode-cn.com/problems/remove-linked-list-elements/
题目描述:
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 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 *dummyHead = new ListNode(0);//设置一个虚拟头节点
dummyHead->next = head;
ListNode *cur = dummyHead;
while(cur->next != nullptr)
{
if(cur->next->val == val)
{
ListNode * tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}else{
cur = cur->next;
}
}
return dummyHead->next;
}
};