def reverse_linked_list_2(ll: LinkedList) -> LinkedList: """Only difference to before: Here I use prev, curr, nex pointers, while before we used curr, nex, over_nex pointers. Both methods work but the pointer positions are shifted by one where place in the linked list. This second method is arguably nicer.""" if not ll.head or not ll.head.next: return ll prev = None curr = ll.head while curr: nex = curr.next curr.next = prev prev = curr curr = nex ll.head = prev return ll
def reverse_linked_list(ll: LinkedList) -> LinkedList: """Reverse a linked list in place. Given is a LinkedList represented by a head node. Returned should be a linked list in reversed order without buffering the results in-between.""" if not ll.head or not ll.head.next: return ll curr_node = ll.head next_node = curr_node.next curr_node.next = None while next_node: over_next = next_node.next next_node.next = curr_node curr_node = next_node next_node = over_next ll.head = curr_node return ll
def split(linked_list): if linked_list == None and linked_list.head == None: left_half = linked_list right_half = None return left_half, right_half else: size = linked_list.size() mid = size // 2 mid_node = linked_list.node_at_index(mid - 1) left_half = linked_list right_half = LinkedList() right_half.head = mid_node.next_node mid_node.next_node = None return left_half, right_half
def merge(left, right): merged = LinkedList() merged.add(0) current = merged.head left_head = left.head right_head = right.head while left_head or right_head: # left_head [None] rigth_head [head 1 => 2 => None] if left_head is None: current.next_node = right_head right_head = right_head.next_node # left_head [head 1 => 2 => None] rigth_head [None] elif right_head is None: current.next_node = left_head left_head = left_head.next_node else: # left_head [head 5 => 2 => None] rigth_head [head 3 => 4 => 1 => None] left_data = left_head.data right_data = right_head.data if left_data < right_data: current.next_node = left_head left_head = left_head.next_node else: current.next_node = right_head right_head = right_head.next_node current = current.next_node head = merged.head.next_node merged.head = head return merged