while cur.next is not None:
            # always delete the next node of cur
            if cur.next.val == val:
                # jump over next node of cur
                cur.next = cur.next.next
                # todo: Attention: after delete node, cur do not move
            else:
                # todo: Attention: cur move to next node only in this case
                cur = cur.next

        return pre_head.next


if __name__ == "__main__":
    from tools.linked_list import LinkedList

    data = [1, 2, 6, 3, 4, 5, 6]
    value = 6
    # data = [1, 1]
    # value = 1

    linked_list = LinkedList(data)
    head1 = linked_list.create()
    linked_list.print_list(head1)

    head_new = Solution().removeElements(head1, value)

    linked_list.print_list(head_new)

Example #2
0
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return head
        pre = None
        cur = head
        while cur is not None:
            next = cur.next

            # cur.next point to pre
            cur.next = pre
            # pre point to cur
            pre = cur
            # cur point to next
            cur = next

            # the next loop, next point to cur.next

        return pre


if __name__ == "__main__":
    from tools.linked_list import LinkedList
    linked_list = LinkedList(range(1, 6))
    test_head = linked_list.create()

    linked_list.print_list(test_head)
    reversed_head = Solution().reverseList(test_head)
    linked_list.print_list(reversed_head)
        :type head: ListNode
        :rtype: ListNode
        """
        return self.answer(head)

    def answer(self, head):
        if head is None:
            return head
        cur = head
        while cur.next is not None:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next

        return head


if __name__ == "__main__":
    from tools.linked_list import LinkedList

    data = [1, 1, 2, 3, 3]
    linked_list = LinkedList(data)
    head1 = linked_list.create()

    new_head = Solution().deleteDuplicates(head1)

    linked_list.print_list(new_head)


Example #4
0
                cur = cur.next
        if cur is not None:
            cur.next = None
        return head


if __name__ == "__main__":
    from tools.linked_list import LinkedList

    l1 = [1, 2, 3]
    l2 = [1, 3, 5]
    l3 = [2, 3, 9]

    l1 = [1, 2, 2]
    l2 = [1, 1, 2]

    linked_list_1 = LinkedList(l1)
    linked_list_2 = LinkedList(l2)
    # linked_list_3 = LinkedList(l3)

    head_1 = linked_list_1.create()
    head_2 = linked_list_2.create()
    # head_3 = linked_list_3.create()

    # test_lists = [head_1, head_2, head_3]
    test_lists = [head_1, head_2]

    head_new = Solution().mergeKLists(test_lists)

    linked_list_1.print_list(head_new)