def rearrange_linked_list(self, head: ListNode) -> ListNode: # find middle of the linked list slow, fast = head, head head_backup = head prev = slow while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next #print(slow.val) # reverse second half of the linked list rev_head = self.reverse_linked_list(slow) #print(rev_head.val) prev.next = None # rearrange the linked list while head and rev_head: head_next = head.next rev_head_next = rev_head.next head.next = rev_head rev_head.next = head_next head = head_next rev_head = rev_head_next # return head of linked list return head_backup
def reverse_linked_list(self, head: ListNode) -> ListNode: prev = None while head: _next = head.next head.next = prev prev = head head = _next return prev
def partition(self, head, x): # write your code here dummy = ListNode(0) dummy.next = head pre = insert_node = dummy while head: if head.val < x: if insert_node.next != head: pre.next = head.next node = insert_node.next insert_node.next = head head.next = node head = pre.next insert_node = insert_node.next else: insert_node = head pre = head head = head.next else: pre = head head = head.next return dummy.next