剑指offer4. 从尾到头打印链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiangxianghehe/article/details/88871870

牛客网链接:从尾到头打印链表
题目:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路1:
挨个遍历往vector首部插值,最后把vector输出。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        if(!head)
            return vec;
        while(head!=nullptr)
        {
            vec.insert(vec.begin(),head->val);
            head = head->next;
        }
        return vec;
    }
};

思路2:
挨个遍历往vector插值,最后把vector逆序输出。

代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        if(!head)
            return vec;
        ListNode *p = head;
        while(p!=nullptr)
        {
            vec.push_back(p->val);
            p = p->next;
        }
        
        return vector<int>(vec.rbegin(), vec.rend());
    }
};

思路3:
借助栈先进后出的特性:先遍历链表把值压入栈,再弹出放入vector即可。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        stack<int> s;
        if(!head)
            return vec;
        while(head!=nullptr)
        {
            s.push(head->val);
            head = head->next;
        }
        while(!s.empty())
        {
            vec.push_back(s.top());
            s.pop();
        }
        return vec;
    }
};

猜你喜欢

转载自blog.csdn.net/xiangxianghehe/article/details/88871870
今日推荐