Python solution with detailed explanation


  • 0
    G

    Solution

    Partition List https://leetcode.com/problems/partition-list/?tab=Description

    1. Use dummy node to create two lists for less than and greater than. Then join them.
    2. Use an example to run through this code.
    class Solution(object):
        def partition(self, head, x):
            """
            :type head: ListNode
            :type x: int
            :rtype: ListNode
            """
            if head == None:
                return None
            dummy_before = d_temp1 = ListNode(-1)
            dummy_after = d_temp2 = ListNode(-1)
            while head:
                if head.val < x:
                    d_temp1.next = head
                    d_temp1 = head
                else:
                    d_temp2.next = head
                    d_temp2 = head
                head = head.next
            d_temp1.next = dummy_after.next
            d_temp2.next = None
            return dummy_before.next
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.