Any good python solution?


  • 4
    I

    I began to study python recently, and want to practice it with leetcode. But, for now, my code is very c/c++ style, as you can see it below. Hope to read some good, python-style solution. Your answer will be appriciated! Thx.

     #Definition for singly-linked list.
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        # @param two ListNodes
        # @return a ListNode
        def mergeTwoLists(self, l1, l2):
            result = ListNode(-1)
            cur = result
            while(l1 and l2):
                if l1.val <= l2.val:
                    cur.next = l1
                    l1 = l1.next
                else:
                    cur.next = l2
                    l2 = l2.next
                cur = cur.next
            l3 = l1 and l1 or l2
            cur.next = l3
            return result.next;

  • 0
    H

    your code is very good , I learned from you
    l3 = l1 and l1 or l2, I just know this is legal for object


  • 0
    R

    Orz... I used while loop for append left Nodes.

    I think your code is better.

        while l1 is not None:
            sentinel.next = l1
            l1 = l1.next
            sentinel = sentinel.next
        while l2 is not None:
            sentinel.next = l2
            l2 = l2.next
            sentinel = sentinel.next
    

  • 0
    Z

    Hi! Could you please explain what does the last three lines do? "l3 = l1 and l1 or l2
    cur.next = l3". Thanks!


  • 0
    Z

    Also, do you need to consider a 2nd case where l1 or l2 contains more items ?


  • 0
    C

    The "while (l1 and l2)" case will include the conditions where l1 and l2 left, so after this while loop you can just connect the remaining part of l1 or l2 to the end.


Log in to reply
 

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