python 从尾到头打印链表
生活随笔
收集整理的這篇文章主要介紹了
python 从尾到头打印链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
從尾到頭打印鏈表
輸入一個鏈表的頭節(jié)點,從尾到頭反過來返回每個節(jié)點的值 (用數組返回)。示例 1:輸入:head = [1,3,2] 輸出:[2,3,1]提供三種題解
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:"""解題思路一: 遞歸解法1.f(-r) = f(head.next) + head.val2.f(head.next) 為遞歸函數解題思路二: 利用棧的特性,先入后出1.遍歷鏈表,不停的入棧2.不停的彈出棧,并把值放到數組中解題思路三: 1.先翻轉整個鏈表2.再順序輸出"""# 解題思路一def reversePrint(self, head: ListNode) -> List[int]:result = list()self.reverseTrave(head, result)return resultdef reverseTrave(self, head, result):if not head:return self.reverseTrave(head.next, result)result.append(head.val)# 解題思路二def reversePrint(self, head: ListNode) -> List[int]:stack = list()result = list()# 遍歷入棧while head:stack.append(head.val)head = head.next# 遍歷出棧while stack:result.append(stack.pop())return result# 解題思路三def reversePrint(self, head: ListNode) -> List[int]:new_head = Noneresult = list()# 翻轉鏈表while head:per = head.nexthead.next = new_headnew_head = headhead = per# 遍歷翻轉后的鏈表while new_head:result.append(new_head.val)new_head = new_head.nextreturn result總結
以上是生活随笔為你收集整理的python 从尾到头打印链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 斐波那契数列
- 下一篇: python 三步问题