从尾到头打印链表——【一天一道算法题】

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

代码里:

#coding:utf-8
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        l = []
        for i in listNode:
            l.insert(0, i)
        return l

a= [1,2,3]
ss = Solution()
print(ss.printListFromTailToHead(a))

猜你喜欢

转载自blog.csdn.net/qq_35462323/article/details/82842404