6/07/2020

[LeetCode] 86. Partition List

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

Create 2 linked lists.  Add node which's value less than x to the first list.  Add node which's value equal or larger than x to the second list. Then append the second linked list to the first linked list.  Finally, return the first linked list as result.

# 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: ListNode, x: int) -> ListNode:
        less = ListNode(0)
        pless = less
        
        larger = ListNode(0)
        plarger = larger
        
        p = head
        
        while p:
            if p.val < x:
                pless.next = p
                pless = pless.next
            else:
                plarger.next = p
                plarger = plarger.next
            
            p = p.next
        
        pless.next = None
        plarger.next = None
        
        pless.next = larger.next
        
        return less.next
        

No comments:

Post a Comment