Python - 链表问题

Python - Linked list issue

我正在尝试做一个leetcode并在我的电脑上测试它,但是我得到一个错误说他找不到上面class中写的curr.next。

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

你能帮我吗我知道我做错了什么但找不到问题所在。 (我是新手):)

问题是您需要创建 ListNode 对象,而不仅仅是一个普通的列表:


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)

可以创建一个函数,以类似的方式从一个列表创建一个链表。但这里有一个粗略的实现!

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
            curr.next = prev
            prev = curr
            curr = temp
        return prev

    def printLinkedList(self, head):
        temp = head
        while(temp):
            print(temp.val)
            temp = temp.next

# create linked list
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
head.next.next.next.next.next = ListNode(6)

# reverse and print
s = Solution()
new_head = s.reverseList(head)
s.printLinkedList(new_head)