剑指offer题目3:从尾到头打印链表。

题目描述

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

解答思路

这题很典型的考到了链表反转。

从这题我立刻去查了一下链表反转是怎么做的,最简单的就是用递归。

function revert(ListNode head) {
    if (head != NULL && head->next != NULL) {
        revert(head->next);
        head->next->next = head;
        head->next = NULL;
    }
}

实现代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> value;
        if(head != NULL) {
            value.insert(value.begin(), head->val);
            if(head->next != NULL) {
                vector<int> other = printListFromTailToHead(head->next);
                value.insert(value.begin(),other.begin(),other.end());  
            }
        }
        return value;
    }
};
posted @ 2019-03-27 10:15  {-)大傻逼  阅读(163)  评论(0)    收藏  举报
欢迎转载,转载请注明本文地址。