newbee123
newbee123

Reputation: 31

LeetCode problem 21: Merge Two Sorted Lists - the first list I create is never processed

I create two linked lists but the first one is never processed in mergeTwoList():

class ListNode:
    def __init__(self,data):
        self.data = data
        self.next = None

def mergeTwoList(l1: ListNode, l2: ListNode) -> ListNode:
        
        cur = ListNode(0)
        ans = cur

        while(l1 and l2):

            print("in loop 1 and 2 :")
            if(l1.data > l2.data):
                print("in if 1 :")
                cur.next = l2
                l2 = l2.next
            else:
                print("in if 2 :")
                cur.next = l1
                l1 = l1.next
            cur = cur.next
        while(l1):

            print("in loop 1  :")
            cur.next = l1
            l1 = l1.next
            cur = cur.next
        while(l2):
            print("in loop  2 :")
            cur.next = l2
            l2 = l2.next
            cur = cur.next
        
        return ans.next


if __name__ == "__main__":
    l1_1 = ListNode(1)
    l1_2 = ListNode(2)
    l1_3 = ListNode(3)

    l1_1.next = l1_2
    l1_2.next = l1_3

    l2_1 = ListNode(4)
    l2_2 = ListNode(5)
    l2_3 = ListNode(6)

    l2_1.next = l2_2
    l2_2.next = l2_3

    while(l1_1 is not None):
        print(l1_1.data)
        l1_1 = l1_1.next

    print("<------>")

    answer = mergeTwoList(l1_1,l2_1)

    while(answer is not None):
        print(answer.data)
        answer = answer.next

Result :

1
2
3
<------>
in loop 2 :
in loop 2 :
in loop 2 :
4
5
6

It never goes through first while condition --> while(l1 and l2)

I am doubting it has got something to do with class invocation in Python but not sure. Any help will be appreciated. If I put this method inside a class and then invoke it outside it works. But the above code is failing.

Upvotes: 1

Views: 121

Answers (1)

pygame
pygame

Reputation: 131

At the end of you first loop:

   while(l1_1 is not None):
        print(l1_1.data)
        l1_1 = l1_1.next

l1_1 is None, and passed to your function mergeTwoList, l1 is None and so your first loop in the function is not entered.

Upvotes: 1

Related Questions