題目描述如下:
思路描述:
這是一道簡單的鏈表題目,我開始用了頭插法,但是時間開銷過大,因此進行了優化,分爲以下幾種方法給大家講解
方法一:使用頭插法,我們可以直接使用列表的插入方法,每次插入數據,只插入在首位
代碼如下:
1 # -*- coding: utf-8 -*- 2 """ 3 @time: 2020/6/19 9:14 4 @author: ZFJ 5 @contact: [email protected] 6 @software: PyCharm 7 @file: 從尾到頭打印鏈表.py 8 """ 9 10 11 # Definition for singly-linked list. 12 # class ListNode(object): 13 # def __init__(self, x): 14 # self.val = x 15 # self.next = None 16 17 class Solution(object): 18 def reversePrint(self, head): 19 """ 20 :type head: ListNode 21 :rtype: List[int] 22 """ 23 result = [] 24 while head: 25 result.insert(0, head.val) 26 head = head.next 27 return result
方法二:通常,這種情況下,我們不希望修改原鏈表的結構。返回一個反序的鏈表,這就是經典的“後進先出”,我們可以使用棧實現這種順序。每經過一個結點的時候,把該結點放到一個棧中。當遍歷完整個鏈表後,再從棧頂開始逐個輸出結點的值,給一個新的鏈表結構,這樣鏈表就實現了反轉。
1 class Solution(object): 2 def reversePrint(self, head): 3 """ 4 :type head: ListNode 5 :rtype: List[int] 6 """ 7 stack = [] 8 # 當鏈表不爲空時,我們就入棧 9 while head: 10 stack.append(head.val) 11 head = head.next 12 # 存儲出棧的結果 13 result = [] 14 # 當棧不爲空 15 while stack: 16 result.append(stack.pop()) 17 return result