Leetcode Problem Solving Reorder List original problem
One-way linked list l0→l1→ ... →ln-1→ln converted to l0→ln→l1→ln-1→l2→ln-2→ ... form, which takes a node from the head and a node from the tail until the original linked list is converted into a new linked list.
Note the point:
- Don't apply for extra space
- Do not modify the value of a node
Example:
Input: {1,2,3,4}
Output: {1,4,2,3}
Thinking of solving problems
Since it is a one-way linked list, it is difficult to take elements from the tail, so we have to reverse the list, and because we are taking elements from both ends, we only need to reverse the second half of the list. We first get the middle node of the linked list by a fast and slow pointer, and we truncate the list. Then the second half of the linked list is flipped, and then the elements are extracted from the two linked lists in turn to connect. Note that it is important to note which linked list is longer when truncating, and do not omit elements when merging.
AC Source
class solution(object): def reorderlist(self, head): "" " : Type head:ListNode:rtype:void does not return anything, modify head in-place instead. """ if notHeadreturn # splitFast = Slow = Head whileFast andFast.next:slow = Slow.next Fast = Fast.next.next Head1, head2 = head, Slow.next slow. Next =None # ReverseCur, pre = head2,None whileCur:nex = Cur.next Cur.next = Pre Pre = cur cur = NEX# MergeCur1, CUR2 = Head1, pre whileCur2:nex1, nex2 = Cur1.next, Cur2.next cur1.next = cur2 Cur2.next = nex1 cur1 , CUR2 = Nex1, nex2if__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Reorder List