ZhongKuo0228 / study

0 stars 0 forks source link

206. Reverse Linked List #89

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago
  1. newHead 為倒敘最後一個 node
  2. cur 代表 iterate 到的 node
  3. 一開始 newHead 為 None,表示最後應該指向的位置
  4. 逐步 iterate,把 newHead 一路變為 cur,再做相應轉換
# 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]:
        cur = head
        new_head = None
        while cur:
            next_node = cur.next
            cur.next = new_head
            new_head = cur
            cur = next_node
        return new_head