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

题目描述:

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

解题思路:

链表的遍历只能从头向尾进行,要从尾到头输出,考虑用栈。先从头到尾遍历一次链表,同时将值进栈,再清空栈,同时将值存入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> res;
        stack<int> s;
        ListNode* cur = head;
        if(head == NULL)
            return res;
        while(cur != NULL)
        {
            s.push(cur->val);
            cur = cur->next;
        }
        while(!s.empty())
        {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/LJ-LJ/p/10583983.html