value = modulo if n1: value += n1.value if n2: value += n2.value result = linkedlist.Node(value % base) if n1 != None or n2 != None: digit = AddListsRecursively(None if n1 == None else n1.next, None if n2 == None else n2.next, value / base) result.setNextNode(digit) return result l1 = linkedlist.CreateList([7, 1, 6]) l2 = linkedlist.CreateList([5, 9, 2]) l3 = linkedlist.CreateList([1, 5, 6]) l4 = linkedlist.CreateList([2, 3, 6, 7]) l5 = linkedlist.CreateList([9, 7, 8]) l6 = linkedlist.CreateList([6, 8, 5]) print SumLists(l1, l2), SumLists(l3, l4), SumLists(l5, l6) print SumLists2(l1, l2), SumLists2(l3, l4), SumLists2(l5, l6) res = AddListsRecursively(l1.head, l2.head, 0) res_list = linkedlist.LinkedList() res_list.setHead(res) print res_list
import linkedlist def GetIntersectingNode(l1, l2): curr1 = l1.head curr2 = l2.head while curr1: while curr2: if curr1 == curr2: return curr1 curr2 = curr2.next curr1 = curr1.next n1 = linkedlist.Node(3) n2 = linkedlist.Node(7) l1 = linkedlist.CreateList([1, 2, 3]) l1.addNode(n1) l2 = linkedlist.LinkedList() l2.addNode(linkedlist.Node(1)) l2.addNode(n1) l2.addNode(linkedlist.Node(7)) l2.addNode(linkedlist.Node(8)) print n1 print GetIntersectingNode(l1, l2)
def RemoveDups(l): current = l.head while current: runner = current while not runner.next == None: if current.value == runner.next.value: runner.next = runner.next.next else: runner = runner.next current = current.next def RemoveDups2(l): previous = None current = l.head unique_els = [] while current: if current.value in unique_els: previous.next = current.next else: unique_els.append(current.value) previous = current current = current.next l = linkedlist.CreateList(["d", "c", "c", "c", "d", "b"]) #RemoveDups(l) RemoveDups2(l) print l
else: right_part.add(current.value) current = current.next if last_node_left: last_node_left.next = right_part.head return left_part else: return right_part def Partition2(l, x): last_node_left = l.head current = l.head previous = l.head while current: if current.value < x: previous.next = current.next node = linkedlist.Node(current.value) node.next = l.head l.head = node previous = current current = current.next l = linkedlist.CreateList([9, 7, 3, 6, 9, 1]) print Partition1(l, 6) l = linkedlist.CreateList([9, 7, 3, 6, 9, 1]) Partition2(l, 6) print l
curr = l.head length = 0 while curr: length += 1 curr = curr.next return length def FindNth(l, n): curr = l.head pos = 0 while curr: pos += 1 if pos == n: return curr.value curr = curr.next def ReturnKthToLast2(l, k): values = [] curr = l.head while curr: values.append(curr.value) curr = curr.next return values[-1 * k] l = linkedlist.CreateList(["a", "b", "c", "d", "e", "f"]) print ReturnKthToLast(l, 2) print ReturnKthToLast2(l, 2)