[剑指Offer]从尾到头打印链表

本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/02/target-offer-reverse-print-linked-list.html  作者: Suixin

链表的基础知识+Python实现四种链表

题目描述

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

解题思路

  1. 正常的思路就是先从前至后依次将链表的元素append到一个list中,最后再取list的逆。当然可以直接每次ls.insert(0, value)
  2. 特殊输入测试:空链表。

代码

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

猜你喜欢

转载自blog.csdn.net/weixin_43269020/article/details/88045322
今日推荐