Leetcode 86. Partition List

Problem

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Algorithm

Use two lists to save the values that number bigger than x and less than x, respectively. Then combine them in order.

Code

# 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:
        if not head:
            return head
        
        l_less = []
        l_greq = []
        
        p = head
        while p:
            if p.val < x:
                l_less.append(p.val)
            else:
                l_greq.append(p.val)
            p = p.next
        
        p = head
        
        for v in l_less:
            p.val = v
            p = p.next
            
        for v in l_greq:
            p.val = v
            p = p.next
            
        return head

你可能感兴趣的:(解题报告)