[S]O-06 从尾到头打印链表
问题描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
解决方案:
method1:列表再反转
列表append再反转reverse或者[::-1]都可以
列表反转:
l.reverse()则已经反转了l本身,l.reverse()的值为null,不是反转结果。l[::-1]也是对列表l进行了反转
# 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]:
# method 1
stack=[]
while head:
tack.append(head.val)
head=head.next
stack.reverse()
return stack
# 或者删掉 stack.reverse()用下面这句
#return stack[::-1]
method2 :栈pop
和method1差不多,只是利用了栈的思想pop
# 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]:
# solution two: 栈
stack = []
while head: # push
stack.append(head.val)
head = head.next
res = []
while stack: # pop
res.append(stack.pop())
return res
method3递归
递归
# 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]:
# solution three: 递归
return self.reversePrint(head.next) + [head.val] if head else []
结果:
-----------2020/12/14–除了递归其他都好理解----------