1.描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
2.想法:
2.1 此题比较简单,因为不知道链表的大小,所以先顺序遍历链表,将值存入序列中,然后再将序列中的值倒过来。
2.2 也可以先遍历链表,记录结点个数,然后再给数组从后往前赋值,但是这种方法在python里面没有必要。
2.3 然后就是堆栈,先将元素入栈,然后pop出来。
2.4 也可以用递归,先输出最里层,然后一层层向外,达到了反向的效果。(这也是我没想到的)
3.答题:
3.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]
"""
a=[]
while head != None:
a.append(head.val)
head = head.next
a.reverse()
return a
逆序输出也可以用切片:a[::-1]
3.2 获取个数后赋值
# Definition for singly-linked list.
# class ListNode(object):
# 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]
"""
mark = head
index = 0
while mark != None:
index += 1
mark = mark.next
a=index*[0]
for i in range(index):
a[index-i-1] = head.val
head = head.next
return a
不推荐,因为简单问题复杂化了,不过也是一种硬解的思路。
3.3 栈
# 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]
"""
a=[]
b=[]
while head != None:
a.append(head.val)
head = head.next
while len(a):
b.append(a.pop())
return b
3.4 递归
# 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]
"""
if head != None:
return []
return self.reversePrint(head.next) + [head.val]
递归嘛,大家都知道,耗费时间肯定比较多,但是思路很好。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof