輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
示例 1:
輸入:head = [1,3,2] 輸出:[2,3,1]
開始前的意外
經過初步嘗試後,發現輸入的head竟然是
ListNode{val: 1, next: ListNode{val: 3, next: ListNode{val: 2, next: None}}}
而ListNode並不是Python自帶的數據類型,所以非常奇怪。直到發現了代碼原始模板中被註釋的幾行:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
想來這應該是約定俗稱的了,下次要注意。
解題思路
首先,根據初始代碼,可知head.val能夠返回頭節點的值;
head.next則能夠訪問下一個節點。
因此,通過構建輔助棧,將所有節點的value按照從前到後的順序放入到輔助棧中;
之後,再利用列表倒置[::-1]的方法先入後出倒置返回即可。
代碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
inverse_head = []
while(head):
inverse_head.append(head.val) # 訪問值
head = head.next # 下一個節點
return inverse_head[::-1] # 倒置
注:
1. [::-1]求列表倒置的原因參見:https://blog.csdn.net/qazwsxrx/article/details/106909177
總結:
做題前注意看輔助函數。