LenleDaytoy

剑指offer-6从尾到头打印链表

题目:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
1.利用列表
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        array1=[]
        while listNode!=None:
            array1.append(listNode.val)
            listNode=listNode.next
         
        return array1[::-1]

2.

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        array1=[]
        while listNode!=None:
            array1.insert(0,listNode.val)
            listNode=listNode.next
         
        return array1

3.递归法

不推荐这种嵌套函数的方法,虽然结果是对的

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        result = []    #这个result放在printListFromTailToHead上面就不能被他所返回
        def solutions(Node):
            if Node:
                solutions(Node.next)
                result.append(Node.val)
        solutions(listNode)
        return result  

 推荐这种方法,可以写一个初始化函数,定义一个列表

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

  

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        array1=[]
        while listNode!=None:
            array1.append(listNode.val)
            listNode=listNode.next
         
        return array1[::-1]

posted on 2020-04-20 16:12  LenleDaytoy  阅读(110)  评论(0编辑  收藏  举报

导航