class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def delete_node(self, node):
        """
        update the current node value with the value of the next and delete the next node.
        @Runtime: 56 ms

        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        if node is None or node.next is None:
            return
        node.val = node.next.val
        node.next = node.next.next

if __name__ == '__main__':
    solution = Solution()
    head = ListNode(1)
    head.next = ListNode(2)
    node3 = head.next.next = ListNode(3)
    node3.next = ListNode(4)

    solution.delete_node(node3)

    print_linkedlist(head)
Example #2
0
        new_head = head
        while head and head.val == val:
            head = head.next
            new_head = head
        if not new_head:
            return None

        # remove elements with value in the list
        node = new_head
        while node:
            if node.next and node.next.val == val:
                node.next = node.next.next
            else:
                node = node.next
        return new_head


if __name__ == '__main__':
    solution = Solution()
    head1 = ListNode(1)
    head1.next = ListNode(2)
    head1.next.next = ListNode(2)
    head1.next.next.next = ListNode(1)

    new_head1 = solution.remove_elements(head1, 2)

    head2 = ListNode(4)
    new_head2 = solution.remove_elements(head2, 3)

    print_linkedlist(new_head1)
        while head and head.val == val:
            head = head.next
            new_head = head
        if not new_head:
            return None

        # remove elements with value in the list
        node = new_head
        while node:
            if node.next and node.next.val == val:
                node.next = node.next.next
            else:
                node = node.next
        return new_head


if __name__ == '__main__':
    solution = Solution()
    head1 = ListNode(1)
    head1.next = ListNode(2)
    head1.next.next = ListNode(2)
    head1.next.next.next = ListNode(1)

    new_head1 = solution.remove_elements(head1, 2)

    head2 = ListNode(4)
    new_head2 = solution.remove_elements(head2, 3)

    print_linkedlist(new_head1)