python3基础——列表翻转

方法:list[::1]

例子:[1,2,3,4]翻转后为[4,3,2,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
        L = []
        if listNode is None:
            return []
        elif listNode.next is None:
            return listNode.val
        else:
            while listNode.next is not None:
                L.append(listNode.val)
                listNode = listNode.next
            L.append(listNode.val)
            return L[::-1]

猜你喜欢

转载自blog.csdn.net/melody113026/article/details/80773443