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 not listNode:return []
stack = []
cur = listNode
while cur != None:
stack.append(cur.val)
cur = cur.next
res = []
while len(stack) > 0:
res.append(stack.pop())
return res
#递归解法
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if not listNode:return []
res = []
def helper(node):
if node.next:
helper(node.next)
res.append(node.val)
helper(listNode)
return res
考点
- 考查对单向链表的理解和编程能力;
- 考查对循环、递归和栈3个相互关联的概念和理解。