Remove Linked List Elements

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

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param val, an integer
    # @return a ListNode
    def removeElements(self, head, val):
        # Write your code here
        dummy = ListNode(0)
        dummy.next = head

        head = dummy

        while head and head.next:
            if head.next.val == val:
                head.next = head.next.next
            else:
                head = head.next
        return dummy.next

Last updated

Was this helpful?