剑指offer 面试题06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ret;
        ListNode *pNode = head;
        stack<int> s;
        while(pNode!=nullptr)
        {
            s.push(pNode->val);
            pNode = pNode->next;
        }
        while(!s.empty())
        {
            ret.push_back(s.top());
            s.pop();
        }
        return ret;
    }
};

这里结合了链表和堆栈,先遍历链表,逐个将元素压进栈中,直到链表指针指向空,然后再逐个将栈内元素弹出,并push_back到新建的vector中并返回,stack s可以创建申明栈;s.push(pNode->value)入栈s.pop出栈,s.top为栈顶元素。

你可能感兴趣的:(剑指offer 面试题06. 从尾到头打印链表)