题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
例:
输入:head = [1,3,2]
输出:[2,3,1]
方法一:暴力
遍历链表,将元素值依次存入数组 ans,再将数组中元素翻转
# 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):
ans = []
while head != None:
ans.append(head.val)
head = head.next
left, right = 0, len(ans)-1
while left < right:
ans[left], ans[right] = ans[right], ans[left]
left += 1
right -= 1
return ans
方法二:递归
先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出
# 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):
return self.reversePrint(head.next) + [head.val] if head else []