剑指offer 从尾到头打印链表

本内容为牛客网,剑指offer题目: 从尾到头打印链表

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 20:13:56 2019

@author: Administrator
剑指offer第三题
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

"""

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

class Solution:
    def printListFromTailToHead(self,listNode):
        result = []
        while True:
            if listNode == None:
                break
            result.append(listNode.val)
            listNode = listNode.next
        result.reverse()    #链表的翻转
        return result
        
if __name__ == '__main__':
    n1 = ListNode(1)
    n2 = ListNode(2)
    n3 = ListNode(3)
    n2.next = n3
    n1.next = n2

    
    solution = Solution()
    result = solution.printListFromTailToHead(n1)
    print(result)

 

posted @ 2019-03-13 14:46  weilongyitian  阅读(105)  评论(0编辑  收藏  举报