リンクリストのヘッドノードを入力し、各ノードの値を端から端まで返します(配列を使用)。
例1:
入力:ヘッド=
[1,3,2]出力:[2,3,1]
制限:
0 <=リンクリストの長さ<= 10000
出典:LeetCode
リンク:https ://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作権は控除ネットワークに属しています。商用転載の正式な許可書に連絡し、非商用転載の出典を明記してください。
アイデア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]:
ans = []
while head != None:
ans.append(head.val)
head = head.next
# print(ans[::-1])
return ans[::-1]