def even_odd_merge(L: LinkedList): curr = L.head final_ll = LinkedList() # if empty linked list return None if not curr: return None else: # if not empty linked list even_head = even_tail = Node(None) odd_head = odd_tail = Node(None) count = 0 while curr: if count == 0: even_tail.next = curr even_tail = even_tail.next elif count == 1: odd_tail.next = curr odd_tail = odd_tail.next curr = curr.next # alternate between 0 and 1 (bitwise operation) count ^= 1 # make sure odd_tail which is at end of final_ll is None # attach odd to even by connecting odd head to even tail # set final linkedlist to even head odd_tail.next = None even_tail.next = odd_head.next final_ll.head = even_head.next return final_ll
def list_pivoting(l:LinkedList,x:int): # 3 nodes with head and iteration pointers(tail) # 1 for less, equal, and greater less_head = less_iter = Node(None) equal_head = equal_iter = Node(None) greater_head = greater_iter = Node(None) # empty linkedlist new_ll=LinkedList() # pointer to input list head curr = l.head # Populates the three lists # based on comparisons to input list # add node to node lists and traverse iteration pointers to corresponding next while curr: if curr.data < x: less_iter.next = curr less_iter = less_iter.next elif curr.data == x: equal_iter.next = curr equal_iter = equal_iter.next else: # curr.data > x. greater_iter.next = curr greater_iter = greater_iter.next curr = curr.next # Combines the three lists. # attach greater to equal and attach equal to less, return greater_iter.next = None equal_iter.next = greater_head.next less_iter.next = equal_head.next new_ll.head = less_head.next return new_ll
node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6) node7 = Node(7) node8 = Node(8) node0.next = node1 node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 node7.next = node8 node8.next = node3 l1.head = node0 print(has_cycle(l1)) print("\n") print(cycle_start(l1)) print("\n") print(cycle_length(l1)) # cycle start and cycle length both have slow and fast at index 1 and 2 not 0 and 1