栈
借助栈存放链表的每个元素,再将元素放进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> ret;
if(head == nullptr)
return ret;
stack<int> st;
ListNode* cur = head;
while(cur)
{
st.push(cur->val);
cur = cur->next;
}
while(!st.empty())
{
ret.push_back(st.top());
st.pop();
}
return ret;
}
};
逆置数组
先将链表中的数据拷贝到vector中,再将vector中的元素进行逆置。
递归方式
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
void _printListFromTailToHead(ListNode* head, vector<int>& ret)
{
if(head == nullptr)
return;
_printListFromTailToHead(head->next, ret);
ret.push_back(head->val);
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
_printListFromTailToHead(head, ret);
return ret;
}
};