LeetCode 203. Remove Linked List Elements 删除链表中得的元素

1.题目

删除链表中所有值为val的节点。

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

2.实现

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == nullptr)
            return nullptr;
        
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        
        while(cur != nullptr)
        {
            if(cur->val == val) //相等时将这个点剔除
                pre->next = cur->next;
            else                
                pre = cur;
            cur = cur->next;
        }
        
        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/u014128608/article/details/92845709