打敗演算法 —— 反轉連結串列
本文參考
出自LeetCode上的題庫 —— 反轉連結串列,該題比較簡單,但是反轉的思想會在很多場景中出現,因此記錄一下
https://leetcode-cn.com/problems/reverse-linked-list/
反轉連結串列問題
給你單鏈表的頭節點 head ,返回反轉後的連結串列
示例1:
輸入:head = [1,2,3,4,5]
輸出:[5,4,3,2,1]
示例 2:
輸入:head = [1,2]
輸出:[2,1]
示例 3:
輸入:head = []
輸出:[]
解題思路
只需要增加一個指標記錄前一個結點的資訊就能夠實現反轉,官方題解還提供了遞迴的解法,類似於之前"排序列表"的遞迴解法。不過用遞迴的思想反而使解題過程變得複雜,本文只記錄迴圈解法
迴圈解法
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
while
tmp = head.next
head.next = pre
pre = head
head = tmp
return pre