Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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) 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading