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

2019-04-02  本文已影响0人  云中的Jason

3. 从尾到头打印链表

题目描述

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

解题思路:

解答:

/*
 *  struct ListNode {
 *        int val;
 *        struct ListNode *next;
 *        ListNode(int x) :
 *              val(x), next(NULL) {
 *        }
 *  };
 */

// 解法1:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ans;
        stack<int> nodes;
        ListNode* pNode = head;
        while(pNode != NULL)
        {
            nodes.push(pNode -> val);
            pNode = pNode -> next;
        }
        while(!nodes.empty())
        {
            ans.push_back(nodes.top());
            nodes.pop();
        }
        return ans;
    }
};
//解法2:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ans;
        ListNode* pNode = head;
        while(pNode != NULL)
        {
            ans.insert(ans.begin(), pNode -> val);
            pNode = pNode -> next;
        }
        return ans;
    }
};

大家有兴趣可以访问我的个人博客,不定时更新一些内容哦!

图片来自必应壁纸
上一篇 下一篇

猜你喜欢

热点阅读