本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/02/target-offer-reverse-print-linked-list.html 作者: Suixin
题目描述
输入一个链表的头节点,按链表值从尾到头的顺序返回一个ArrayList。
解题思路
- 正常的思路就是先从前至后依次将链表的元素
append
到一个list中,最后再取list的逆。当然可以直接每次ls.insert(0, value)
; - 特殊输入测试:空链表。
代码
Python(2.7.3)
# -*- 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
if not listNode:
return []
ls = []
current = listNode
while current is not None:
ls.append(current.val)
current = current.next
return ls[::-1]
运行时间:30ms
占用内存:5860k