# -*- coding:utf-8-*-
# classListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
最先想到的就是用list的[;;-1]来返回倒序值,把listNode的按顺序装到list,但是注意listNode已经定义好了是链表,不能用以下方式 for i in range
classSolution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
res = []
fori in listNode:
res.append(i)
returnres[::-1]
而要用链表指针的形式,赋值给下一个指针指向的位置, 下一个位置没有值则listNode.next为空
classSolution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
res = []
while listNode:
res.append(listNode.val)
listNode = listNode.next
returnres[::-1]
classSolution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
res = []
whilelistNode:
res.append(listNode.val)
listNode = listNode.next
res.reverse()
returnres
还可以考虑用传统的栈 先进后出的思维,用两个list res[]和stack[],一个stack[]装listNode的值然后pop()出来,一个res[]装stack[] pop出来的值,但是这样我个人感觉
class Solution:# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
res = []
stack = []
while listNode:
stack.append(listNode.val)
listNode = listNode.next
while stack:
res.append(stack.pop())
return res