剑指offer-从尾到头打印链表

水题,可以立刻想到的方法是

1.从头到尾遍历,依次入栈,然后出栈。时间复杂度和空间复杂度都是O(n)

2.先反转链表,然后遍历。时间复杂度O(n),空间O(1)

3.先放到数组,再倒序存一遍,和方法1思想相同,也是最蠢的方法。

其他方法自己想吧...

最蠢的我贴出最蠢的代码- -

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        ListNode *hp = head;
        int cnt = 0;
        while(hp){
            cnt++;
            hp = hp->next;
        }
        int *tmp = new int[cnt + 1], ii = 0;
        hp = head;
        while(hp){
            tmp[ii++] = hp->val;
            hp = hp->next;
        }
        for(int i = ii - 1; i >= 0; --i){
            res.push_back(tmp[i]);
        }
        delete[] tmp;
        return res;
    }
};
View Code
原文地址:https://www.cnblogs.com/dupengcheng/p/7660014.html