Skip to content

Latest commit

 

History

History
 
 

203. Remove Linked List Elements

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Related Topics:
Linked List

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/remove-linked-list-elements/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode dummy, *tail = &dummy;
        while (head) {
            auto p = head;
            head = head->next;
            if (p->val == val) continue;
            tail->next = p;
            tail = p;
        }
        tail->next = NULL;
        return dummy.next;
    }
};