1. 程式人生 > >Python :從尾到頭列印連結串列 【牛客網:劍指offer】

Python :從尾到頭列印連結串列 【牛客網:劍指offer】

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回從尾部到頭部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        out=[]
        head=listNode
        while head!=None:
            out.append(head.val)
            head=head.next
        out.reverse()
        return out

方式一:使用reversed()函式

  1. a=[1,2,3,4,5,6,7,8,9]  
  2. b=list(reversed(a))  
  3. print b  

注意:reversed()函式返回的是一個迭代器,而不是一個List,需要再使用List函式轉換一下。

方式二:使用sorted()

  1. a=[1,2,3,4,5,6,7,8,9]  
  2. c=sorted(a,key=None, reverse=True)  
  3. print c  

注意:其中reverse=True是按降序排列,reverse=False是按照升序排列

方式三: 使用分片

  1. a=[1,2,3,4,5,6,7
    ,8,9]  
  2. d=a[::-1]  
  3. print d  

注意:其中[::-1]代表從後向前取值,每次步進值為1