剑指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):
# write code here
result = []
self.printListFromTailToHeadDetail(listNode,result)
return result
def printListFromTailToHeadDetail(self, listNode,result):
if listNode != None:
self.printListFromTailToHeadDetail(listNode.next,result)
result.append(listNode.val)
C++源码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
if (head!= nullptr){
printListFromTailToHeadDetail(head,v);
}
return v;
}
void printListFromTailToHeadDetail(ListNode* head,vector<int>& v) {
if (head!= nullptr){
printListFromTailToHeadDetail(head->next,v);
v.push_back(head->val);
}
}
};