1. 程式人生 > >LeetCode 206.反轉鏈表(Python3)

LeetCode 206.反轉鏈表(Python3)

class listnode def fin sel nbsp turn 當前 ever

題目:

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

進階:
你可以叠代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?

解答:

方法一:原地反轉。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ‘ListNode‘) -> ‘ListNode‘:
        # cur當前節點
        # pre為當前節點的上一個節點,反轉後的下一個節點
        # nex為當前節點的下一個節點,反轉後的上一個節點
        cur = head
        pre = None
        while cur:
            # 節點原地反轉
            nex = cur.next
            cur.next = pre
            pre = cur
            # 進入下一個要反轉的節點
            cur = nex
        return pre
            

  

LeetCode 206.反轉鏈表(Python3)