![](https://img.haomeiwen.com/i13792534/781fad0bc88574ea.jpg)
微信图片_20191221160845.jpg
############# 【第一种遍历】###############
class Solution:
def __init__(self):
self.result = []
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
while listNode:
self.result.insert(0,listNode.val)
listNode = listNode.next
return self.result
############# 【第二种,先反转,再遍历】###############
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if listNode is None:
return []
if listNode.next is None:
return listNode
pre = listNode
cur = listNode.next
last = listNode.next.next
pre.next = None
while last != None:
cur.next = pre
pre = cur
cur = last
last = last.next
cur.next = pre
result = []
while cur != None:
result.append(cur.val)
cur = cur.next
return result
网友评论