143. Reorder List

143. Reorder List

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        mydict={}
        curr=head
        cnt=0
        while curr:
            mydict[cnt]=curr
            cnt+=1
            curr=curr.next
        l,r=0,cnt-1
        dummy=ListNode(0,head)
        prev=dummy
        while l<=r:
            prev.next=mydict[l]
            if l==r:
                mydict[l].next=None
                return dummy.next
            mydict[l].next=mydict[r]
            mydict[r].next=None
            prev=mydict[r]
            l+=1
            r-=1
        return dummy.next

你可能感兴趣的:(leetcode)