剑指offer---链表值从尾到头的顺序返回一个ArrayList

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

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

1、使用栈来缓存链表的数据

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ArrayList;
        stack<int> st;
        ListNode *p = head;
        int tmp;
        while(p)
        {
            tmp = p->val;
            st.push(tmp);
            p = p->next;
        }

        while(!st.empty())
        {
            tmp = st.top();
            ArrayList.push_back(tmp);
            st.pop();
        }
        return ArrayList;
    }
};

2、不缓存数据,先存在容器中,然后调用reverse方法反转

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ArrayList;
        stack<int> st;
        ListNode *p = head;
        int tmp = 0;
        while(p != NULL)
        {
            tmp = p->val;
            ArrayList.push_back(tmp);
            p = p->next;
        }

        reverse(ArrayList.begin(), ArrayList.end());
        return ArrayList;
    }
};

猜你喜欢

转载自blog.csdn.net/zh1204190329/article/details/82531253