天天看點

反轉連結清單 python 遞歸_LeetCode 206.反轉連結清單(Python3)

題目:

反轉一個單連結清單。

示例:

輸入: 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