0

So, I came across this question of merging two sorted linked lists on Leetcode. I am just a beginner so was in a fix and thought about referring to answers on the discussion page and stumbled across this small code. However, I am super confused about the 'l1,l2 = l2, l1' line. I did go across the internet and someone did explain using an example, but I still couldn't understand. I'd appreciate it if someone can explain it in layman terms to me, if possible.

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        
        if(l1 == None): return l2
        if(l2 == None): return l1
        
        # Initial
        if(l1.val > l2.val):
            l1, l2 = l2, l1
        
        
        resHead = l1
        while(l1 != None and l2 != None):
                tmp = None
                while(l1 != None and l1.val <= l2.val):
                    tmp = l1
                    l1 = l1.next
                
                tmp.next = l2
                
                l1, l2 = l2, l1
        
        return resHead
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
whybutwhy
  • 7
  • 2

0 Answers0