def pad_list(h1, h2): c1, c2 = h1, h2 l1, l2 = 0,0 while c1 != None: l1 += 1 c1 = c1.next while c2 != None: l2 += 1 c2 = c2.next if l1 < l2: h = Node(0) padding = [0 for _ in xrange(l1 - l2 - 1)] h.append_array(padding) h.append_node(h1) return h, h2 elif l1 > l2: h = Node(0) padding = [0 for _ in xrange(l2 - l1 - 1)] h.append_array(padding) h.append_node(h2) return h1, h else: return h1, h2
""" def remove_duplicate(head): dups = {} curr, prev = head, None while curr != None: if dups.get(curr.data, False) == False: dups[curr.data] = True prev = curr else: prev.next = curr.next curr = curr.next return head head = Node(5) head.append_array([2, 3, 4, 2, 3, 4]) print "remove duplicate [5, 2, 3, 4, 2, 3, 4]", remove_duplicate(head).to_list() == [5, 2, 3, 4] """ Return kth to last Implement an algorithm to find the kth to last element of a singly linked list """ def kth_to_last(head, k): if k == 0: return Node(None) first, second = head, head while k > 0: k -= 1 first = first.next while first != None: first, second = first.next, second.next