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

2019-05-02  本文已影响0人  vouv

题目描述

替换空格

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路

利用栈的思想,通过递归实现

Code

# -*- 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
/*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
}
上一篇下一篇

猜你喜欢

热点阅读