栈思路:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
ListNode *p=NULL;
p=head;
stack<int> stk;
while(p!=NULL){
stk.push(p->val);
p=p->next;
}
while(!stk.empty()){
value.push_back(stk.top());
stk.pop();
}
return value;
}
};
翻转数组
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
ListNode *p=NULL;
p=head;
while(p!=NULL){
value.push_back(p->val);
p=p->next;
}
//reverse(val.begin(),val.end());//c++自带数组
int tmp=0;
int i=0;
int j=value.size()-1;
while(i<j)
{
tmp=value[i];
value[i]=value[j];
value[j]=value[i];
i++;
j--;
}
return value;
}
递归思路:
class Solution {
public:
vector<int> value;
vector<int> printListFromTailToHead(ListNode* head) {
ListNode *p=NULL;
p=head;
while(p!=NULL){
while(p->next!=NULL){
printListFromTailToHead(p->next) ;
}
value.push_back(p->val);
}
return value;
}
};