본문 바로가기

IT/코딩테스트

[Leetcode] 143. Reorder List

728x90

https://leetcode.com/problems/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.
        """

        slow = fast = head
        while fast != None and fast.next != None:
            slow = slow.next
            fast = fast.next.next
        
        prev = None
        node = slow
        while node != None:
            next_node = node.next

            node.next = prev
            prev = node
            node = next_node
        
        first, second = head, prev
        while second.next != None:
            temp1 = first.next
            temp2 = second.next

            first.next = second
            second.next = temp1
        
            first = temp1
            second = temp2
        
        return
728x90