【剑指Offer】03从尾到头打印链表

题目描述

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

时间限制:1秒;空间限制:32768K;本题知识点: 链表

解题思路

思路一

头插法,得到链表的倒序list,正序输出结果。

Python代码:

# -*- 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
        l = []
        while listNode:
            l.insert(0, listNode.val)
            listNode = listNode.next
        return l

思路二

尾插法,得到链表的正序list,利用 l[::-1] 翻转输出结果。

Python代码:

# -*- 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
        l = []
        while listNode:
            l.append(listNode.val)
            listNode = listNode.next
        return l[::-1]
原文地址:https://www.cnblogs.com/yucen/p/9912058.html