【剑指offer】面试题6—从尾到头打印链表

一、题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

二、代码实现

方法一、遍历,存在list中,反转list
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        nodevallist = []
        while listNode:
            nodevallist.append(listNode.val)a
            listNode = listNode.next
        return nodevallist[::-1]
方法二、遍历,记录在stack里,然后pop出来
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        stack = []
        while listNode:
            stack.append(listNode.val)
            listNode = listNode.next
        res = []
        while stack:
            res.append(stack.pop())
        return res
方法三、递归,直到链表尾,再返回
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        
        res = []
        if not listNode: return res
        def recursive(listNode):
            if not listNode.next:
                res.append(listNode.val)
            else:
                recursive(listNode.next)
                res.append(listNode.val)
        recursive(listNode)
        return res

精简后:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        
        res = []
        if not listNode: return res
        def recursive(listNode):
            if listNode.next:
                recursive(listNode.next)
            res.append(listNode.val)
        recursive(listNode)
        return res
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容