AttributeError: 'list' object has no attribute 'val' in linked list LeetCode challenge

Question:

I am trying to solve a LeetCode problem concerning linked lists Merge Two Sorted Lists, but when I test my solution locally, and pass example lists [1,2,3] to my function, I get this error:

AttributeError: ‘list’ object has no attribute ‘val’

What shall I do to fix that?

Here is my code:

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

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        cur = dummy = ListNode()
        while list1 and list2:               
            if list1.val < list2.val:
                cur.next = list1
                list1, cur = list1.next, list1
            else:
                cur.next = list2
                list2, cur = list2.next, list2
                
        if list1 or list2:
            cur.next = list1 if list1 else list2
            
        return dummy.next
    
        
l1 = [1,2,3]
l2 = [1,2,3]
obj = Solution()
print(obj.mergeTwoLists(l1,l2))
Asked By: mahdiahmad

||

Answers:

Code challenge sites like LeetCode, turn the JSON-like input into linked lists for you before calling your solution code. So when you want to run your code locally, outside that framework, you’ll have to convert these standard lists to linked lists first, and after you run the code, you’ll have to turn the returned linked list back to something printable as well:

def createLinkedList(lst):
    head = None
    for val in reversed(lst):
        head = ListNode(val, head)
    return head

def toList(head):
    lst = []
    while head:
        lst.append(head.val)
        head = head.next
    return lst
    
l1 = createLinkedList([1,2,3])
l2 = createLinkedList([1,2,3])
obj = Solution()
print(toList(obj.mergeTwoLists(l1,l2)))
Answered By: trincot