Scribbling

LeetCode: 143. Reorder List 본문

Computer Science/Coding Test

LeetCode: 143. Reorder List

focalpoint 2021. 11. 22. 10:49

Recursion을 이용한 방법

# 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.
        """
        cur = head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        new_head, _ = self.helper(head, count)
        return new_head
        
    def helper(self, head, count):
        if count == 1:
            tail_node = head.next
            head.next = None
            return head, tail_node
        if count == 2:
            tail_node = head.next.next
            head.next.next = None
            return head, tail_node
        new_head, now_tail = self.helper(head.next, count-2)
        next_tail = now_tail.next
        head.next = now_tail
        now_tail.next = new_head        
        return head, next_tail

 

다른 방법

class Solution:
    def reorderList(self, head):
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        new_head = slow.next
        slow.next = None
        
        cur, prev = new_head, None
        while cur:
            nextt = cur.next
            cur.next = prev
            prev = cur
            cur = nextt
        new_head = prev
        
        head1, head2 = head, new_head
        while head2:
            next1 = head1.next
            head1.next = head2
            next2 = head2.next
            head2.next = next1
            head1 = next1
            head2 = next2
        return head