美文网首页
剑指Offer - 3 - 从尾到头打印链表

剑指Offer - 3 - 从尾到头打印链表

作者: vouv | 来源:发表于2019-05-02 14:06 被阅读0次

题目描述

替换空格

输入一个链表,按链表值从尾到头的顺序返回一个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
}

相关文章

网友评论

      本文标题:剑指Offer - 3 - 从尾到头打印链表

      本文链接:https://www.haomeiwen.com/subject/pmlgnqtx.html