剑指 Offer 06. 从尾到头打印链表
说明
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
题解思路
1、双向队列实现先进后出
循环存入队列,再从队尾依次取出来
2、列表逆向输出
递归存入列表,再从列表中逆向输出
代码实现
1、双向队列
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
ans = []
deque = collections.deque()
while head:
deque.append(head.val)
head = head.next
for i in range(len(deque)):
ans.append(deque.pop())
return ans
2、列表
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
ans = []
def dfs(head):
if head:
ans.append(head.val)
dfs(head.next)
dfs(head)
# ans.reverse()
return ans[::-1]