剑指offer6.从尾到头打印链表

剑指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);
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。