輸入一個鏈表,按鏈表值從尾到頭的順序返回一個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;
}
};