牛客网剑指offer的题:这里先定义链表,因为python没有专门的链表数据结构,可以参考这里的链表操作
这里我采用递归的方法,最上链表的指针域和值都已经给出,直接调用就行。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if listNode is None:
return []
return self.printListFromTailToHead(listNode.next) + [listNode.val]
# write code here
也可以不用递归的方法,将链表值循环插入列表,再将列表反转就行。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
a = []
if listNode is None:
return a
while listNode.next is not None:
a.append(listNode.val)
listNode = listNode.next
a.append(listNode.val)
a.reverse()
return a
# write code here