我想在本地机器上实现 Leetcode 问题,因为我是初学者,并且想掌握 python 编程。我认为在本地解决问题有助于我详细地理解问题。这就是 Leetcode 206 的起点。反转链表.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
## your code goes here...
leetcode 平台上有很多 YT 视频解释该算法以及如何解决该算法,但没有一个视频教如何从头开始实现它。 所以,我尝试做以下事情:
##
from typing import List
class ListNode:
def __init__(self, head = None, next = None):
self.head = head
self.next = next
def __repr__(self):
return self.head
##
class Solution:
def __init__(self):
self.head = ListNode()
def reverseList(self, nums: ListNode)-> ListNode:
prev, cur = None, self.head
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
当我在leetcode中提交时,解决方案本身是正确的。但是当我按照以下方式实现自己的 main 时,我得到以下结果。
## main1
if __name__ =="__main__":
nums = [1,2,3,4,5]
sol = Solution()
ans = sol.reverseList(nums)
print(ans)
输出如下所示:
<__main__.ListNode object at 0x000002E6E5CFB940>
您能帮助我如何在本地正确实现 main 并查看对象数据类型吗?我面临树和列表节点类型问题的问题。 非常感谢。
from typing import Optional
class ListNode:
def __init__(self, data=None):
self.data = data
self.next = None
# This is for converting a list to a linked list.
# The output is the head of the linked list
def list_to_linked_list(values):
head = None
tail = None
for val in values:
node = ListNode(val)
if head is None:
head = tail = node
else:
tail.next = node
tail = node
return head
# This is for converting a linked list to a list. The input is the head.
# The output is the list converted.
def linked_list_to_list(head):
curr = head
res = []
while curr:
res.append(curr.data)
curr = curr.next
return res
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
head = list_to_linked_list([0, 1, 2, 3])
solution = Solution()
print(linked_list_to_list(solution.reverseList(head)))
# Output: [5, 4, 3, 2, 1]