# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = Nonea = ListNode(1)b = ListNode(2)a.next = b# 有關鏈表 ...
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
a = ListNode(1)
b = ListNode(2)
a.next = b
# 有關鏈表的題,基本上思路都是很好想的,主要是代碼的實現
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 定義一個當前節點和前驅節點
cur,prev = head,None
# 然後迴圈遍歷鏈表節點。
while cur:
# 當前節點的指針指向前驅節點,當前節點向後移,前驅結點向後移
cur.next,cur,prev = prev,cur.next,cur
# 最後返回前驅節點。
return prev
A = Solution()
print(A.reverseList(a))