剑指Offer(三):从尾到头打印链表[链表]

牛客网刷题笔记记录。

一.题目

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

二.思路分析

链表的遍历方式为从前往后,要求的输出为从后往前。这明显是一个先进后出的问题,由此想到利用栈进行解决本问题。

三.编程实现

C++

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> temp;
        vector<int> result;
        ListNode* node=head;
        //依次入栈
        while(node!=NULL)
        {
            temp.push(node->val);
            node=node->next;
        }
        //依次出栈并进行存储
        while(!temp.empty())
        {
            result.push_back(temp.top());
            temp.pop();
        }
        
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_39568744/article/details/88409617
今日推荐