输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接: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]:
tmplist = []
node = head
while node:
tmplist.append(node.val)
node = node.next
tmplist.reverse()
return tmplist
'''
这是错的
return tmplist.reverse()
如果想直接返回,而且不改变原列表元素顺序
return tmplist[::-1]
'''
这里踩了个小坑,感觉不是第一次了,记录一下,就是list.reverse()是没有返回值的,但是会改变列表中元素的顺序。
还有一种递归法,很简洁。思路为先走到链表的末端,然后回溯时依次将值加入链表。
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
作者:jyd
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。