zoukankan      html  css  js  c++  java
  • python3从尾到头打印链表

    题目描述

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

    方法一:通过栈实现

    # -*- 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
            stack = []
            while listNode != None:
                stack.append(listNode.val)
                listNode = listNode.next
            ArrayList =[]
            while stack:
                ArrayList.append(stack.pop())
            return ArrayList
    

     方法二:通过递归实现

    # -*- 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
            # @listNode: 头结点
            if listNode is None:
                return []
            return self.printListFromTailToHead(listNode.next) + [listNode.val]
    
  • 相关阅读:
    23.课程应用接口
    22.课程页面设计
    21.手机接口
    20.云通讯
    19.JWT
    18.权限认证
    解决github下载慢的终极方法
    vs code 配置c/c++环境
    Python 字符编码处理总结
    Python编码
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9486807.html
Copyright © 2011-2022 走看看