一、前言
最近在刷力扣上的題目,之前也刷過很多次,一邊刷一邊忘,很是苦惱。
爲什麼邊學邊忘,很大程度是沒有應用場景,只是被動的進行填鴨式學習。
爲了提高學習效率,覺得還是得堅持寫博客,一方面強化記憶,第二強迫自己創造應用場景,學習知識的同時也在產生知識。
二、題目
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list/
三、單鏈表的相關知識
參考我的其他博文: 【python鏈表】之單向鏈表詳解
四、學習參考視頻
一分鐘教你鏈表反轉
五、解答方法
"""
反轉一個單鏈表。
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
last = None # 前置節點
while head:
tmp = head.next # 保存當前節點的下一個節點,不可缺,因爲後面更改了當前節點的next指向
head.next = last # 更改當前節點的next爲上一個節點
last = head # 將上一個節點移動到當前節點
head = tmp # 當前節點移動到下一個節點
# head.next, last, head = last, head, head.next ,簡寫樣式,提高運行速度
return last
if __name__ == '__main__':
# 創建一個1-5的鏈表
a = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5,)))))
obj = Solution()
Node = obj.reverseList(a)
while Node:
print(Node.val)
Node = Node.next