《剑指offer3- 从末尾到头打印链表》

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 
本质上是逆转链表
 
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> list;
        head = this->reverseList(head);
        while(head){
            list.push_back(head->val);
            head = head->next;
        }
        return list;
    }
    

    
    ListNode* reverseList(ListNode* head){
        if(!head || !head->next){
            return head;
        }
        ListNode* last = NULL;
        while(head){
            ListNode* next = this->reverseNode(last, head);
            last = head;
            head = next;
        }
        return last;
    }
    
    ListNode* reverseNode(ListNode* last, ListNode* cur){
        ListNode* next = cur->next;
        cur->next = last;
        return next;
    }
    
    //递归的方式会导致堆栈溢出
    void dumpListReverse(ListNode* head, vector<int> &list){
        
        if(!head && !head->next)
        {
            this->dumpListReverse(head->next, list);
        }
        list.push_back(head->val);
    }
};

  

posted @ 2018-11-02 19:26  兜兜有糖的博客  阅读(224)  评论(0编辑  收藏  举报