Confusion about the python solution


  • 0
    K

    I was able to get accepted, but I dont understand one line of the code.

    class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
    
    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))
    
    class Solution:
    # @param head, a ListNode
    # @param x, an integer
    # @return a ListNode
    def partition(self, head, x):
        dummySmaller, dummyGreater = ListNode(-1), ListNode(-1)
        smaller, greater = dummySmaller, dummyGreater
        
        while head:
            if head.val < x:
                smaller.next = head
                smaller = smaller.next
            else:
                greater.next = head
                greater = greater.next
            head = head.next
            
        smaller.next = dummyGreater.next
        # I dont understand the following one line. What are we doing here ? When we do greater=greater.next
       # in the while loop, I thought greater.next already makes the last node as "None". 
        greater.next = None
        return dummySmaller.next

  • 0
    Y

    The node stored in greater at the end of the code may not be the actual last one in the list we're given. We make it the last one by that line of code.


Log in to reply
 

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