# Reverse the nodes from head up to (but not including) end, and link the # old head, which becomes the last reversed node, to tail_next. # @param head, a ListNode # @param tail_next, a ListNode or None # @param end, a ListNode or None # @return the new head of the reversed part defreverse_list(head, tail_next, end): prev = tail_next cur = head while end != cur: cur_next = cur.next cur.next = prev prev = cur cur = cur_next return prev
classSolution:
# @param head, a ListNode # @return nothing defreorderList(self, head):
ifNone == head: return cur = head count = 0 whileNone != cur: cur = cur.next count += 1 if count <= 2: return
half_count = (count - 1) / 2 cur2 = head for i inrange(0, half_count): cur2= cur2.next cur2_next = cur2.next cur2.next = None cur2 = reverse_list(cur2_next, None, None)
cur1 = head time_count = int(count / 2) for i inrange(0, time_count): cur2_next = cur2.next cur2.next = cur1.next cur1.next = cur2 cur1 = cur2.next cur2 = cur2_next