My Python solution using a guard node

• ``````def mergeTwoLists(self, l1, l2):
if not l1 and not l2:
return None

node = guard_node = ListNode(0)

while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next

if l1 or l2:
node.next = l1 or l2

return guard_node.next``````

• Thanks for sharing! Very clean code and easy to understand :)

• Could you please explain more about if l1 or l2: p.next = l1 or l2? I've never seen expression like this before. What happened if there multiple nodes of l1 or l2 left? Thanks a lot!

• it assigns a value of l1 or l2 to node.next if either of l1 or l2 has valid (not null) data. e.g a = 1 or None (or) a = None or 1 assigns a value of 1 to a.

• amazing! I never known that the judge condition can be wrote as "if l1 or l2: ... l1 or l2", thank for your tip!!!

• ``````if not l1 and not l2:
return None
``````

you can remove it and it is exactly my soluton then:)

change

`````` if l1 or l2:
node.next = l1 or l2
``````

to
node.next = l1 or l2

• Nice solution, here is a shorten version of your code:

``````def mergeTwoLists(self, l1, l2):
while l1 and l2:
if l1.val < l2.val:
head.next = ListNode(l1.val)  # or l1
l1 = l1.next
else:
head.next = ListNode(l2.val)  # or l2
l2 = l2.next
return dummy.next``````

• Very nice code !

• Here is a more condensed version:

``````def mergeTwoLists(self, l1, l2):
node = dummy = ListNode(-1)
while l1 and l2:
if l1.val >= l2.val:
l1, l2 = l2, l1
node.next = l1
l1 = l1.next
node = node.next
node.next = l1 or l2
return dummy.next
``````

• @totolipton what ListNode(0) does? I am new to programming so just want to understand if someone give me details of it.

• @zorro13 It's just a dummy node

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