pythonlinked-listissue-tracking

Python - Linked list issue


I am trying to do a leetcode and test it on my computer, but I get an error saying that he can't find the curr.next which is written in the class above.

class ListNode():
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(ListNode):
    def reverseList(self, head):
     # Two pointer solution itertaively where T O(n) and M O(1)
        val = 0
        next = None
        prev, curr = None, head
        while curr:
            temp = curr.next  <--- here is the error
            curr.next = prev
            prev = curr
            curr = temp
        return prev

head = Solution()
head.reverseList([1,3,3,4,5,5,6])

could you please help me I know im doing something wrong but can't find the issue. (im a newbie) :)


Solution

  • The issue is that you need to create ListNode object not just a normal list as you do :

    
    class ListNode():
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next
    class Solution(ListNode):
        def reverseList(self, head):
         # Two pointer solution itertaively where T O(n) and M O(1)
            val = 0
            next = None
            prev, curr = None, head
            while curr:
                temp = curr.next  <--- here is the error
                curr.next = prev
                prev = curr
                curr = temp
            return prev
    
    head = Solution()
    node7 = ListNode(val=6)
    node6 = ListNode(val=5, next=node7)
    node5 = ListNode(val=5, next=node6)
    node4 = ListNode(val=4, next=node5)
    node3 = ListNode(val=3, next=node4)
    node2 = ListNode(val=3, next=node3)
    node1 = ListNode(val=1, next=node2)
    head.reverseList(node1)