from linkedList import LinkedList _set = set() def loopDetection(valMyList): vValue = None for i in valMyList: if not (i.value in _set): _set.add(i.value) else: vValue = i.value break return vValue _list = LinkedList() _list.addSeveral(["A", "B", "C", "D", "E", "C"]) print(loopDetection(_list))
''' Implement an algorithm to delete a node in the middle (i.e. any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. ''' from linkedList import LinkedList def delete_middle_node(node): node.value = node.next.value node.next = node.next.next ll = LinkedList() ll.addSeveral([1, 2, 3, 4]) middle_node = ll.add(5) ll.addSeveral([7, 8, 9]) print(ll) delete_middle_node(middle_node) print(ll)
''' Given two (singly) linked lists, determine if the two lists intersect. Return the inter- secting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting ''' from linkedList import LinkedList def intersection(valList1, valList2): shorter = valList2 if (len(valList1) > len(valList2)) else valList2 larger = valList2 if (len(valList2) > len(valList1)) else valList1 print(shorter) print(larger) for i in shorter: for j in larger: if i.value == j.value: return i.value _vl1 = LinkedList() _vl2 = LinkedList() _vl1.addSeveral([1, 2, 3, 4]) _vl2.addSeveral([0, 0, 0, 2]) print(intersection(_vl1, _vl2))
def createPartition(valLinkedList, partition): vFirstPartition = LinkedList() vNode = valLinkedList.head vSecondPartition = LinkedList() while (vNode != None): if (vNode.value < partition): #add the node to the vFirstPartition vFirstPartition.add(vNode) elif (vNode.value > partition): #print(vNode) vSecondPartition.add(vNode) elif (vNode.value == partition and vNode.next == None): vSecondPartition.add(Node) vNode = vNode.next #print(vFirstPartition) #print(vSecondPartition) return vFirstPartition.mergeLists(vSecondPartition) ll = LinkedList() ll.addSeveral([3, 5, 8, 5, 10, 2]) #print(ll) print(createPartition(ll, 5)) #print("-------------") #print(ll)