本题来自《剑指offer》 从尾到头打印链表
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { std::vector<int> result; //存放结果值 std::stack<ListNode*> nodes; //栈,存放其节点的值 ListNode* phead = head; int val; while (phead != NULL){ //遍历链表 nodes.push(phead); //将节点加入到栈中 phead = phead->next; } while (!nodes.empty()){ //从栈中取数据 val = nodes.top()->val; result.push_back(val); nodes.pop(); } return result; } };
原文:https://www.cnblogs.com/missidiot/p/10751135.html