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)
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)
: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)
cur_b = head_b while j > 0: cur_b = cur_b.next j -= 1 while cur_a is not None and cur_b is not None: if cur_a.val == cur_b.val: cur_a = cur_a.next cur_b = cur_b.next if cur_a is None and cur_b is None: return True return False if __name__ == "__main__": a = [4, 1, 8, 4, 5] b = [5, 0, 1, 8, 4, 5] from tools.linked_list import LinkedList l_a = LinkedList(a) l_b = LinkedList(b) head_a = l_a.create() head_b = l_b.create() print(Solution().getIntersectionNode(head_a, head_b)) # todo: test not passed