Leetcode 203. Remove Linked List Elements

Lintcode 452. 删除链表中的元素

Posted by Olivia Liu on November 5, 2019 | 阅读:

Description

Remove all elements from a linked list of integers that have value val.

删除链表中等于给定值 val 的所有节点。

Examples

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

Answer

Traverse from the beginning and skip the node with the same value as val.

Time Complexity

O(n)

Code

C++

class Solution {
public: 
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* res = new ListNode(0);
        res->next = head;
        head = res;
        while(head->next)
        {
            if(head->next->val == val) head->next = head->next->next;
            else head = head->next;
        }
        return res->next;
    }
};