Scribbling

LeetCode: 86. Partition List 본문

Computer Science/Coding Test

LeetCode: 86. Partition List

focalpoint 2021. 10. 6. 16:26

간단하면서도 재밌는 문제

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        smaller_train = ListNode()
        s_ptr = smaller_train
        bigger_train = ListNode()
        b_ptr = bigger_train
        cur = head
        while cur != None:
            if cur.val < x:
                s_ptr.next = cur
                s_ptr = cur
            else:
                b_ptr.next = cur
                b_ptr = cur
            cur = cur.next
        b_ptr.next = None
        s_ptr.next = bigger_train.next
        return smaller_train.next