python 反转链表
生活随笔
收集整理的這篇文章主要介紹了
python 反转链表
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
反轉(zhuǎn)鏈表
定義一個函數(shù),輸入一個鏈表的頭節(jié)點,反轉(zhuǎn)該鏈表并輸出反轉(zhuǎn)后鏈表的頭節(jié)點。示例:輸入: 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 = Noneclass Solution:"""解題思路一: 遞歸法解題思路二: 頭插法"""# 遞歸法解題def reverseList(self, head: ListNode) -> ListNode:if not head or not head.next:return headnew_head = self.reverseList(head.next)head.next.next = headhead.next = Nonereturn new_head# 頭插法解題def reverseList(self, head: ListNode) -> ListNode:new_head = Nonewhile head:per = head.next # 記錄下一個節(jié)點head.next = new_head # 把new_head 賦值給head.next new_head = head # 把head 重新賦值給new_headhead = per # 跳到下一個節(jié)點return new_head總結(jié)
以上是生活随笔為你收集整理的python 反转链表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 三步问题
- 下一篇: python 数值的整数次方