剑指offer:03 从尾到头打印链表

题目描述

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

基本思想

利用栈先进后出、后进先出的特点,利用list的insert()方法,不断往list头(栈顶)插入新元素insert(0,val),最后return l。

Python - 栈的应用

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

Python - append()+切片

class Solution:

    # 返回从尾部到头部的列表值序列,例如[1,2,3]

    def printListFromTailToHead(self, listNode):

        # write code here

        l = []

        head = listNode

        while head:

            l.append(head.val)

            head = head.next

        return l[::-1]

Python的insert()方法和append()方法

#!/usr/bin/python 

aList = [123, 'xyz', 'zara', 'abc'] 

aList.insert( 3, 2009) 

print "Final List : ", aList

注意insert()方法和append()、sort()方法是没有返回值的

你可能感兴趣的:(剑指offer:03 从尾到头打印链表)