题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
//方法1:递归
vector<int> ans;
void recur(ListNode* head)
{
if(head==NULL)
return;
recur(head->next);
ans.emplace_back(head->val);
}
vector<int> printListFromTailToHead(ListNode* head)
{
recur(head);
return ans;
}
//方法2:vector的reverse()
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> ans;
ListNode* h =head;
while(h!=NULL)
{
ans.push_back(h->val);
h=h->next;
}
reverse(ans.begin(),ans.end());
return ans;
}
//方法3:反转链表 (先将反转链表,再依次遍历打印值)
vector<int> printListFromTailToHead(ListNode* head)
{
ListNode* pre=head,*cur=NULL,*temp=NULL;
vector<int> ans;
while(pre!=NULL)
{
temp=pre->next;
pre->next=cur;
cur=pre;
pre=temp;
}
while(cur!=NULL)
{
ans.emplace_back(cur->val);
cur=cur->next;
}
return ans;
}
//方法4:栈