剑指 Offer 06. 从尾到头打印链表
原始题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
解题思路:
这道题比较简单,遍历链表,要求从尾到头返回一个列表,所以遍历链表的时候使用双端队列这个数据结构,从头开始插入节点的值即可,题目要求返回的是一个数组。具体实现看代码。
代码实现:
# 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]:
if not head:
return []
queue = collections.deque()
cur_node = head
while cur_node:
queue.appendleft(cur_node.val)
cur_node = cur_node.next
return [x for x in queue]