【剑指offer】从尾到头打印链表(python)
逆序输出列表,arr[::-1]
list[begin_idx: end_idx: step]对列表进行切片操作。从索引 begin_idx 开始,如果 step 为正则向右按 step 的值为步进切片至 end_idx 的前一个元素结束; 如果 step 为负则向左按 step 的值为步进切片至 end_idx 的前一个元素结束。
arr[::-1]就是从头到尾按step=-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
list = []
while listNode:
list.append(listNode.val)
listNode = listNode.next
return list[::-1]
京公网安备 11010502036488号