zoukankan      html  css  js  c++  java
  • 【剑指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]
  • 相关阅读:

    守护线程
    下载图片
    多线程
    self的作用
    设置项目地址环境
    对象 类
    ValueError: urls must start with a leading slash
    mock挡板接口开发
    K&R——第五章 指针与数组
  • 原文地址:https://www.cnblogs.com/yucen/p/9912058.html
Copyright © 2011-2022 走看看