day2-2022.10.25
题目信息来源:
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm
来源:力扣(LeetCode)
剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
题解一:
- 需要注意输入为空的情况
- 这里倒序主要是用了python列表自带的[::-1]倒序实现
- 根据时间,append队尾插入反转最快,insert队首插入次之,+队尾插入反转最慢
- 这里其实是栈的用法
# 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]:
list = []
if head==None:
return []
while head.next!=None:
list.append(head.val)
head = head.next
list.append(head.val)
return list[::-1]
上述的简洁版写法
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
list = []
while head:
list.append(head.val)
head = head.next
return list[::-1]
题解二
递归法,慢的要死,亲测用append的时候不能用,得用+,或许是这个原因
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []。