Leetcode 86. Partition List

📅2023-08-15🧐100

https://leetcode.com/problems/partition-list/

Just initial two linked-list, then traverse the original one, if the value is smaller, save to one of new linked-list, else save to another one.

# 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]:
        
        h1 = ListNode()
        h2 = ListNode()

        cur, cur1, cur2 = head, h1, h2

        while cur:
            if cur.val < x:
                cur1.next = ListNode(cur.val)
                cur1 = cur1.next
            else:
                cur2.next = ListNode(cur.val)
                cur2 = cur2.next
            cur = cur.next

        cur1.next = h2.next
        return h1.next