Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

ex1) Given 1->2->3->4, reorder it to 1->4->2->3.
ex2) Given 1->2->3->4->5, reorder it to 1->5->2->4->3.


Code Block
languagepy
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        
        # collect value serially
        v=[]
        p=head
        while p!=None:
            v.append(p.val)
            p=p.next
        
        # reorder based on the given logic
        i=0
        lcnt=len(v)
        j=lcnt-1
        p=head
        while p!=None:
            p.val = v[i]
            i += 1
            p=p.next
            
            if p!=None:
                p.val = v[j]
                j-=1
                p = p.next