剑指Offer - 3 - 从尾到头打印链表
2019-05-02 本文已影响0人
vouv
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
利用栈的思想,通过递归实现
Code
- 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):
# write code here
if listNode is None:
return []
arr = self.printListFromTailToHead(listNode.next)
arr.append(listNode.val)
return arr
- JavaScript
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
// write code here
if (!head) return []
const arr = printListFromTailToHead(head.next)
arr.push(head.val)
return arr
}