美文网首页
【剑指offer】面试题6—从尾到头打印链表

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

作者: Gaoyt__ | 来源:发表于2019-07-25 23:20 被阅读0次

一、题目描述

输入一个链表,按链表值从尾到头的顺序返回一个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

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/mdclrctx.html