【剑指Offer】 3.从尾到头打印链表 python实现

题目描述

输入一个链表,按链表从尾到头的顺序返回一个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
        answer = []
        head = listNode
        while head:
            answer.append(head.val)
            head = head.next
        return answer[::-1]

第二种解法

-*- 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
        answer = []
        head = listNode
        while head:
            answer.insert(0, head.val)
            head = head.next
        return answer
发布了99 篇原创文章 · 获赞 6 · 访问量 4000

猜你喜欢

转载自blog.csdn.net/weixin_42247922/article/details/103915865