【剑指 Offer】06,从尾到头打印链表。 难度等级:简单。递归法值得研究

文章目录

    • 一、题目
    • 二、我的解法:对 list 逆序
    • 三、递归方法
      • 3.1 递归方法一
      • 3.2 递归方法二

一、题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例:

输入:head = [1,3,2]
输出:[2,3,1]

二、我的解法:对 list 逆序

思路:顺序遍历链表并放到list中,然后对list逆序。

code:

# 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]:
        ans=[]
        while head!=None:
            ans.append(head.val)
            head=head.next
        ans.reverse()
        return ans

注意:直接 return ans.reverse() 的话会返回 null,因为 ans.reverse() 对ans本身进行逆序,没有开辟额外的内存空间,也没有额外使用其他列表。所以 ans.reverse() 没有返回值。

执行结果:

执行用时:44 ms, 在所有 Python3 提交中击败了66.72% 的用户
内存消耗:17.9 MB, 在所有 Python3 提交中击败了34.24% 的用户

三、递归方法

3.1 递归方法一

思路图解:

【剑指 Offer】06,从尾到头打印链表。 难度等级:简单。递归法值得研究_第1张图片
code:

# 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]:
        if head==None:
            return []
        else:
            return self.reversePrint(head.next)+[head.val]

执行结果:

执行用时:120 ms, 在所有 Python3 提交中击败了 13.00% 的用户
内存消耗:27.4 MB, 在所有 Python3 提交中击败了 5.06% 的用户

3.2 递归方法二

code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def __init__(self):
        self.ans=[]
        self.i=0
        self.j=0 

    def reversePrint(self, head: ListNode) -> List[int]:
        self.solve(head)
        return self.ans

    def solve(self, head: ListNode):
        # 每执行一次solve函数,i+1,则遍历一遍haed链表后,i等于链表长度
        if head==None:
            self.ans=[None]*self.i
            return
        self.i+=1

        self.solve(head.next)
        self.ans[self.j] = head.val
        self.j+=1

执行结果:

执行用时:48 ms, 在所有 Python3 提交中击败了 50.14% 的用户
内存消耗:27.5 MB, 在所有 Python3 提交中击败了 5.06% 的用户

你可能感兴趣的:(#,链表,链表,数据结构)